Frage

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.

War es hilfreich?

Lösung

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();

Andere Tipps

Yeah there is a better way you can do what you trying to achieve, just do as follows:

private void cancelButton_Click(object sender, EventArgs e)
{
    Close();
}

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;
       Application.Exit();
   }
   else if (res == DialogResult.No)
   {
       e.Cancel = true;
   }

}

that way you first close the current form which is intuitive to the user and only after that you close the application which will trigger the closing events of the other forms.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top