[英]Firing application exit on Windows shutdown
I have a winforms program which have an "Exit" button which fires an event that performs a clean up and then afterwards fire Application.Exit();
我有一个winforms程序,它有一个“退出”按钮,它触发一个执行清理的事件,然后激活Application.Exit();
to exit the program. 退出程序。
But since the program is a tray application, I often forget to shut down the program using this exit button and just hitting the Windows shutdown instead. 但由于该程序是托盘应用程序,我经常忘记使用此退出按钮关闭程序,而只是按下Windows关闭。 If I do that the event is not called and therefore not cleaning up. 如果我这样做,事件不会被调用,因此不会清理。
My question is: Is there an event I can count on when using different closing methods, like windows shutdown? 我的问题是:当使用不同的关闭方法时,我可以指望一个事件,比如关闭窗口吗?
I have seen I can override OnClosing
- but is this the correct way? 我看到我可以覆盖OnClosing
- 但这是正确的方法吗?
Edit: 编辑:
All answers did work. 所有答案都有效。 But I eventually ended out with: 但我最终以:
Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
I think you could use this: 我想你可以用这个:
void Init()
{
SystemEvents.SessionEnding +=
new SessionEndingEventHandler(SystemEvents_SessionEnding);
}
void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
{
// Do what you need
}
A gool link to read could be this 要读取的gool链接可能是这个
EDITED: This solutions works even in a non form application (console, service, etc...). 编辑:此解决方案甚至可以在非表单应用程序(控制台,服务等)中使用。
Yes, to find different closing methods overriding the OnClosing event will work. 是的,找到覆盖OnClosing事件的不同关闭方法将起作用。 Look at the below code part. 请看下面的代码部分。
protected override void OnFormClosing(FormClosingEventArgs e)
{
try
{
ConfirmClose = true;
base.OnFormClosing(e);
if (e.CloseReason == CloseReason.WindowsShutDown)
{
//Do some action
}
}
}
catch (Exception ex)
{
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.