- In this example, we'll implement a spell check dialog box that allows the user
to change the text in the dialog box and immediately see the changes in the
parent window
- Create a new Windows Forms project in Visual Studio
- Add a new Windows Form called SpellCheckForm
- Add a text box and Close button as shown in the screenshot:
-
The dialog box (
SpellCheckForm
) must first declare a delegate,
a reference to a method whose signature an event handler must match
public delegate void ChangeWordEventHandler(string word);
- Next, the event must be defined (
ChangeWord
) that can be observed by the parent window.
Later when the event is triggered, an event handler matching the ChangeWordEventHandler
delegate will be notified of the event
public event ChangeWordEventHandler ChangeWord;
- Add a
TextChanged
event handler to the text box that triggers
the ChangeWord
event, notifying the parent window of the word that
has been typed:
private void wordTextBox_TextChanged(object sender, EventArgs e)
{
// Notify the parent window to changes in the text box
ChangeWord(wordTextBox.Text);
}
- Finally add a
Click
event handler to the Close button so it
closes the dialog box (setting its DialogResult
will not work since the dialog box
is not going to be shown modally)
private void closeButton_Click(object sender, EventArgs e)
{
Close();
}