C# 捕获应用程序退出事件 - WinForms

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10579446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:22:29  来源:igfitidea点击:

Capturing Application exit event - WinForms

c#winforms

提问by user1387147

Is this possible to capture Windows form close event when clicked on application stop. I know application stop working but is there any method available who will fire in any case when application is closing? I found these methods from google but they are not working:

单击应用程序停止时,是否可以捕获 Windows 窗体关闭事件。我知道应用程序停止工作,但是有什么方法可以在应用程序关闭时在任何情况下触发?我从谷歌找到了这些方法,但它们不起作用:

 AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);  

or

或者

  Application.ApplicationExit += new EventHandler(this.OnApplicationExit); 

Is it possible to get close event when click on application stop button?

单击应用程序停止按钮时是否可以获取关闭事件?

采纳答案by kerrubin

In Program.cs file, you must have those methods beforeApplication.Run :

在 Program.cs 文件中,您必须Application.Run之前拥有这些方法:

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
        AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
        Application.Run(new MainForm());
    }

You can also use the Disposed event on the MainForm (the form used in Application.Run method).

您还可以在 MainForm(Application.Run 方法中使用的表单)上使用 Disposed 事件。