0

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.

4

2 回答 2

1

创建一个新类,例如

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;
    }
}

然后删除Form_Closing事件处理程序并调用

ApplicationCloseHelper.CloseApplication();

直接从Cancel_Click();

于 2014-02-03T18:17:36.573 回答
0

是的,有一种更好的方法可以实现您想要实现的目标,只需执行以下操作:

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;
   }

}

这样,您首先关闭对用户来说很直观的当前表单,然后才关闭将触发其他表单的关闭事件的应用程序。

于 2014-02-03T17:35:46.050 回答