SpellCheckForm
) must first declare a delegate,
a reference to a method whose signature an event handler must match
public delegate void ChangeWordEventHandler(string word);
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;
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); }
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(); }
ChangeWord
event
and launch the dialog box using the Show()
method:
private void button1_Click(object sender, EventArgs e) { SpellCheckForm spellChecker = new SpellCheckForm(); spellChecker.ChangeWord += spellChecker_ChangeWord; spellChecker.Show(); }Note that
Show()
returns immediately unlike ShowDialog()
which blocks until the dialog box is closed
spellChecker_ChangeWord()
event handler which
will change the word in the text box to match the word in the dialog box:
void spellChecker_ChangeWord(string word) { wordTextBox.Text = word; }
spellChecker.ChangeWord += (word) => { wordTextBox.Text = word; };
// spellChecker.ChangeWord += spellChecker_ChangeWord;and run the application again. What happens when you launch the dialog and start typing? Fix this
System.NullReferenceException
by ensuring that ChangeWord
is not null
before "calling" it in the SpellCheckForm
. Make sure
you de-comment the line above before going on
if (ChangeWord != null) ChangeWord(textBox1.Text); // Or simplify with null-conditional operator ChangeWord?.Invoke(textBox1.Text);
SpellCheckForm
:
// Initialize the modeless dialog's text box spellChecker.TheText = label1.Text;
TheText propery's setter also needs to set the dialog box's text box to the given text
private SpellCheckForm spellChecker; private void button1_Click(object sender, EventArgs e) { if (spellChecker == null || spellChecker.IsDisposed) { // Was closed or hasn't been shown yet spellChecker = new SpellCheckForm(); spellChecker.ChangeWord += spellChecker_ChangeWord; // Initialize the modeless dialog's text box spellChecker.TheText = label1.Text; } else { // Already being displayed spellChecker.BringToFront(); } spellChecker.Show(); }