Search code examples
c#winformsformclosing

Trigger OnFormClosing() from MenuItem


I have a simple WinForm Application where I have defined an override for OnFormClosing, to be able to ask for an exit confirmation and close the sql connection. It looks like this:

protected override void OnFormClosing(FormClosingEventArgs e)
    {
        switch (MessageBox.Show(this, "Really quit " + Application.ProductName + "?",
                     Application.ProductName, MessageBoxButtons.YesNo,
                     MessageBoxIcon.Exclamation))
        {
            case DialogResult.Yes:
                con.Close();
                Debug.WriteLine("Connection Closed");
                Debug.WriteLine("Exiting Application");
                Application.Exit();
                break;
            default:
                break;
        }
    }

Unfortunately when I Close the form the "really-quit"-dialog pops up twice. Why is this so?


Solution

  • Use events instead of overriding:

    using System.Windows.Forms;
    
    namespace WindowsFormsApplication2
    {
        public partial class Form1 : Form
        {
            public Form1 ()
            {
                InitializeComponent ();
            }
    
            private void Form1_FormClosing (object sender, FormClosingEventArgs e)
            {
                var result = MessageBox.Show ("My App", "Really quit?", MessageBoxButtons.YesNo);
    
                if (result == DialogResult.Yes)
                {
                    // close connection
                }
                else
                {
                    e.Cancel = true;
                }
            }
        }
    }