R – why form_closing() is firing twice

winforms

I am working on a windows form application. I want to show user a message stating close reason when user clicks "X" button in the main window.With "X" button i mean "close" button in "minimize","maximize" and "close" tray in windows.

I have written this code.

 private void frmIMS_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (MessageBox.Show("This application is closing down because of " + e.CloseReason.ToString() + ". Do you really want to close it ?", "", MessageBoxButtons.YesNo) == DialogResult.No)
        {                
            e.Cancel = true;
        }
        else
        {
            Application.Exit();
        }
    }

Now what happens is,If user clicks no to message box,event is discarded and when user clicks yes,form_closing() fires again and shows other messagebox.So messagebox is shown twice.I want to show it once.Please help and tell why is it firing twice.

Best Answer

You can skip the else part of your application. If your form is main form of application, it will exit anyway. Application.Exit() causes all windows to close. Your "first" close is still pending, so form is not yet closed and Application.Exit() tries to close your form for the second time.

You can try this:

bool closingPending = false;
private void frmIMS_FormClosing(object sender, FormClosingEventArgs e)
{
    if (closingPending) return;
    if (MessageBox.Show("This application is closing down because of " + e.CloseReason.ToString() + ". Do you really want to close it ?", "", MessageBoxButtons.YesNo) == DialogResult.No)
    {                
        e.Cancel = true;
    }
    else
    {
        closingPending = true;
        Application.Exit();
    }
}
Related Topic