如何捕获退出Winforms应用程序的事件?

16
如果用户通过点击退出图标或使用ALT+F4想要退出应用程序,我想弹出一个对话框询问用户是否真的确定要退出。如何在应用程序实际关闭之前捕获此事件?

3
请注意,退出WinForms应用程序并不等同于退出窗体。该问题标题存在误导性。 - nawfal
6个回答

23

查看表单的 OnClosing 事件。

这是从该链接中提取的代码片段,实际上检查文本字段是否发生更改并提示进行保存:

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
   // Determine if text has changed in the textbox by comparing to original text.
   if (textBox1.Text != strMyOriginalText)
   {
      // Display a MsgBox asking the user to save changes or abort.
      if(MessageBox.Show("Do you want to save changes to your text?", "My Application",
         MessageBoxButtons.YesNo) ==  DialogResult.Yes)
      {
         // Cancel the Closing event from closing the form.
         e.Cancel = true;
         // Call method to save file...
      }
   }
}

您可以更改文本以适应您的需求,然后我认为您可能希望根据您的文本将 DialogResult.Yes 切换为 DialogResult.No


这是专门为您修改的代码:

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
   if(MessageBox.Show("Are you sure you want to quit?", "My Application", MessageBoxButtons.YesNo) ==  DialogResult.No)
   {
      e.Cancel = true;
   }
}

请注意:.NET Framework 2.0版本中的OnClosing方法已经过时,请改用OnFormClosing方法。 - reformed

15

您应该订阅Form_Closing事件,在那里发布对话框,如果用户中止关闭操作,则将FormCloseEventArgs.Cancel设置为true。

例如,在Form_Load或使用设计器中订阅事件。

Form1.FormClosing += new FormClosingEventHandler(Form1_Closing);

....
private void Form1_FormClosing(Object sender, FormClosingEventArgs e) 
{
    DialogResult d = MessageBox.Show("Confirm closing", "AppTitle", MessageBoxButtons.YesNo );
    if(d == DialogResult.No)
        e.Cancel = true;
}

根据情况而定并不总是一个好主意,去打扰用户进行这种类型的处理。
如果你有有价值的修改过的数据,并且不想冒失损失更改,那么这总是一个好决定,但如果你只是把它作为关闭操作的确认,那么最好什么都不做。


4
你可以处理Form_ClosingForm_Closed事件。
在Visual Studio中,点击闪电图标并在表单属性列表中向下滚动到这些事件。双击你想要的一个事件,它会为你自动连接该事件。


1

这只是一个表格吗?如果是的话,您可能想使用FormClosing事件,它允许您取消它(显示对话框,然后如果用户选择取消关闭,则将CancelEventArgs.Cancel设置为true)。


0
如果你在谈论 windows forms,那么捕获你的MainWindow

FormClosing 事件应该就足够了,如果你想要阻止关闭,只需将事件处理程序的参数设置为true

例如:

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{

      if(MessageBox.Show("Do you really want to exit?", "My Application",
         MessageBoxButtons.YesNo) ==  DialogResult.No){

                // SET TO TRUE, SO CLOSING OF THE MAIN FORM, 
                // SO THE APP ITSELF IS BLOCKED
                e.Cancel = true;            
      }
   }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接