Search code examples
c#winformsdelegatesshowdialogformclosing

FormClosing delegate not working with ShowDialog() method


In my C# WinForms program I have some forms and I show one of them as a dialog:

MyForm mf = new MyForm();
mf.ShowDialog();

But when I try to assigne a form closing event for them, it is not working;

mf.FormClosing += delegate { MessageBox.Show("Dialog is closed.")};

What is the problem?

P.S: It works fine when I call the form using mf.Show() method.

Thanks.


Solution

  • "Not working" is hopelessly ambiguous. There's a semi-colon missing in your snippet. Having to guess, don't assign the FormClosing event after calling ShowDialog(), that's too late. This works fine:

        private void button1_Click(object sender, EventArgs e) {
            using (var mf = new Form2()) {
                mf.FormClosing += delegate { MessageBox.Show("Dialog is closed."); };
                mf.ShowDialog();
            }
        }