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

标签 c# .net winforms

如果用户想通过单击退出图标或按 ALT+F4 退出应用程序,我想制作一个对话框询问用户是否真的确定要退出。

如何在应用程序实际关闭之前捕获此事件?

最佳答案

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

关于c# - 如何捕获退出 Winforms 应用程序的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11047475/

相关文章:

C#:如何将类属性公开给一个类而不公开给另一个类?

c# - 将 Excel 保存为管道分隔的 CSV(XlFileFormat 枚举)

c# - 如何检查太长的路径?

c# - 获取行号异常

c# - 从 silverlight 调用 Java Web 服务会引发异常

c# - 在 Winforms 中更改 ListBox 的 "selected"颜色?

c# - EWS 获取所有文件夹中未读邮件的数量

c# - LinQ 数据行和列集合 C#

c# - __doPostBack 未作为控件的一部分包含在内

c# - 是否可以在 WinForms 中旋转按钮控件?