c# - Windows 关闭时触发应用程序退出

标签 c# winforms

我有一个 winforms 程序,它有一个“退出”按钮,该按钮触发一个执行清理的事件,然后触发 Application.Exit(); 退出程序。

但由于该程序是一个托盘应用程序,我经常忘记使用此退出按钮关闭程序,而只是点击 Windows 关机。如果我这样做,则不会调用该事件,因此不会进行清理。

我的问题是:在使用不同的关闭方法(例如关闭 Windows)时,是否存在我可以依赖的事件?

我已经看到我可以覆盖 OnClosing - 但这是正确的方法吗?

编辑:

所有答案都有效。但我最终以:

Application.ApplicationExit += new EventHandler(Application_ApplicationExit);

最佳答案

我想你可以用这个:

void Init()
{
    SystemEvents.SessionEnding += 
        new SessionEndingEventHandler(SystemEvents_SessionEnding);
}

void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
{
    // Do what you need
}

一个很好的阅读链接可以是 this

已编辑: 该解决方案甚至适用于非表单应用程序(控制台、服务等...)。

关于c# - Windows 关闭时触发应用程序退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7764565/

相关文章:

c# - 如何警告 Console.Write() 中的错误参数编号?

c# - WCF - 在调用之间共享/缓存数据

c# - C++ 等价于 C# 的内部

c# - 如何使用 Protobuf.net 更改类型成员的 ProtoMember 索引?

c# - 使用 DataTable 时如何对列执行计算?

c# - 为什么 BigInteger.ToString ("x") 为 signed.MaxValue(不含)和 unsigned.MaxValue(含)之间的值添加 0?

c# - 使用单选按钮

c# - 确定自定义 winforms 控件的设计时上下文

c# - 在 UserControl 中公开 DataGridView 的列属性无法正常工作

c# - 窗体 : How to bind the Checkbox item of a CheckedListBox with databinding