如何检测 Windows 关机或注销

问题描述:

我需要检测 Windows 何时关闭(或重新启动)或用户何时注销.我需要在应用程序关闭之前正确关闭应用程序.我注意到在 Windows 关闭日时没有引发退出应用程序事件.

I need to detect when Windows is shutdown (or restarted) or when the user is logging off. I need to properly close the application before the application is closed. I noticed that no exit application event is raised when Windows is closing day.

我阅读了帖子 c# 中是否有办法检测 Windows 关闭/注销并取消该操作(询问用户后)

但我不确定在关闭之前应该在哪里执行操作.谢谢.

but I'm not sure of where I should perform the operations before closing. Thanks.

附上事件处理程序方法SystemEvents.SessionEnding 事件,并且每次引发事件时都会调用您的处理程序方法.如果您愿意,处理此事件将允许您取消挂起的注销或关闭.(虽然这在当前的操作系统中实际上并不像听起来那样工作;有关更多信息,请参阅 此处为 MSDN 文档.)

Attach an event handler method to the SystemEvents.SessionEnding event, and your handler method will be called each time the event is raised. Handling this event will allow you to cancel the pending log off or shut down, if you wish. (Although that doesn't actually work like it sounds in current operating systems; for more information see the MSDN documentation here.)

如果您不想取消活动,而只是对其做出适当的反应,您应该处理SystemEvents.SessionEnded 事件.

If you don't want to cancel the event, but just react to it appropriately, you should handle the SystemEvents.SessionEnded event instead.

您必须确保在应用程序关闭时分离您的事件处理程序,但是,因为这两个都是静态事件.

You must make sure that you detach your event handlers when the application is closed, however, because both of these are static events.