如何检测 Windows 关闭或注销
我需要检测 Windows 何时关闭(或重新启动)或用户何时注销。我需要在应用程序关闭之前正确关闭应用程序。 我注意到 Windows 关闭日时不会引发退出应用程序事件。
我读了帖子 c# 中有没有一种方法可以检测 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.
I read the post Is there a way in c# to detect a Windows shutdown/logoff and cancel that action (after asking the user)
but I'm not sure of where I should perform the operations before closing.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将事件处理程序方法附加到
SystemEvents.SessionEnding
事件,以及每次引发事件时都会调用您的处理程序方法。如果您愿意,处理此事件将允许您取消挂起的注销或关闭。 (尽管这实际上并不像当前操作系统中听起来的那样工作;有关详细信息,请参阅 MSDN 文档此处。)如果您不想取消事件,而只是对其做出适当反应,则应该处理
SystemEvents.SessionEnded
事件反而。但是,您必须确保在应用程序关闭时分离您的事件处理程序,因为这两个事件都是静态事件。
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.)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.
您可以通过 使用本机解决方案pinvoke 如果您的代码未在非交互式会话(例如系统服务)中运行:
You can use a native solution via pinvoke if your code is not running in a non-interactive session (such as a system service):
现在你应该使用这样的东西:
Now you should use something like this: