如何捕获退出 Winforms 应用程序的事件? [英] How do I catch the event of exiting a Winforms application?

查看:31
本文介绍了如何捕获退出 Winforms 应用程序的事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If the user wants to exit the application by clicking on the exit icon or by ALT+F4, I'd like to make a dialog box questioning the user if he/she is really sure about exiting.

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

How do I capture this event before the application is actually closed?

推荐答案

查看 OnClosing 表单事件.

以下是该链接的摘录,实际检查文本字段的更改并提示保存:

Here is an extract from that link actually checks for a change on a text field and prompts a save:

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.

You can change the text to suit your needs, and then also I think you might want to switch the DialogResult.Yes to DialogResult.No based on your text.

这里有一些专门为您修改的代码:

Here is some modified code just for you:

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

这篇关于如何捕获退出 Winforms 应用程序的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆