Search code examples
c#winformsformclosing

Application.exit() calls FormClosingEvent of different Windows Form


I have a C# application that has multiple forms. On every form I have Cancel button and the top right (x) button. For every form, I have created a cancelButton_Click() which goes like this:

private void cancelButton_Click(object sender, EventArgs e)
{
    Application.Exit();
}

This one calls the formClosing function which goes like this:

private void FormLoginPage_Closing(object sender, FormClosingEventArgs e)
{
   string exitMessageText = "Are you sure you want to exit the application?";
   string exitCaption = "Cancel";
   MessageBoxButtons button = MessageBoxButtons.YesNo;
   DialogResult res = MessageBox.Show(exitMessageText, exitCaption, button, MessageBoxIcon.Exclamation);
   if (res == DialogResult.Yes)
   {
       e.Cancel = false;

   }
   else if (res == DialogResult.No)
   {
       e.Cancel = true;
   }
}

Similarly I have created customized formClosing functions for all forms, since I want to handle Closing events differently for all forms.

However, when I click on Cancel button for say Form2, the control goes to Form1 Closing event function. Is there a better way to implement this? Please suggest.


Solution

  • Create a new class something like

    public static class ApplicationCloseHelper
    {
        public static void CloseApplication()
        {
            if (UserIsSure())
            {
                Application.Exit();
            }
        }
    
        private static bool UserIsSure()
        {    
            string exitMessageText = "Are you sure you want to exit the application?";
            string exitCaption = "Cancel";
            MessageBoxButtons button = MessageBoxButtons.YesNo;
            DialogResult res = MessageBox.Show(exitMessageText, exitCaption, button, MessageBoxIcon.Exclamation);
            return res == DialogResult.Yes;
        }
    }
    

    then remove the Form_Closing event handlers and call

    ApplicationCloseHelper.CloseApplication();
    

    directly from Cancel_Click();