C# - 如何检测 Windows 关闭/注销并取消该操作(询问用户后)
一些解释:对于我正在从事的项目,我必须编写一个在后台运行的程序,检测文件的更改,并将修改后的文件上传到 Web 服务以使其可供其他人使用。如果不是用户修改大文件并决定在编辑后立即关闭计算机的情况,这是相当简单的同步。
我可以取消上传并等待下次重新启动才能上传,但我可以想象用户第二天早上将文件从网络下载到另一台计算机,并且不明白为什么他昨晚所做的更改不存在。
因此,我的想法是检测用户何时注销或重新启动 Windows,如果我正在上传,只需询问用户“我们仍在同步您发送的文件 Foo.txt
”刚刚更改。您确定要重新启动吗?只有重新启动计算机后,其他人才能看到您所做的更改!”。如果用户拒绝,我需要取消重新启动/注销
这可能吗?
Some explanation: for a project I'm working on I have to write a program that is running in the background, detects changes to files, and uploads the modified files to a web service to make it available to others. Quite simple synchronization if it were not for the case when a user modifies a big file and decides to shutdown its computer right after the edit.
I could cancel the upload and wait for the next reboot to do the upload, but I can imagine the user downloading the file from the web to another computer the next morning and don't understanding why his changes from last night aren't there.
So my idea was to detect when the users logs off or reboots Windows, and if I'm in the middle of an upload, just asking the user "We're still synchronizing file Foo.txt
that you just changed. Are you sure you want to reboot ? You're changes won't be available to others until you restart your computer !". If the users says no, I'd need to cancel the reboot/loging off
Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有一个名为
SystemEvents
的静态类公开了此行为:http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.aspx
但是,它无法区分某些操作,并且不会暂停操作系统进程超时警卫。我使用过一次,但注册表中配置的默认超时有点短,因此可能需要增加。
长话短说,这一切都感觉有点老套。
There is a static class called
SystemEvents
that exposes this behaviour:http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.aspx
However, it cannot differentiate between certain actions and doesn't pause the OS process time-out guard. I used it once, but the default time-out as configured in the registry is a little short so will likely need increasing.
To cut a long story short, it all felt a little hackish.
要添加@Adam的答案,如果您需要区分注销和关闭/重新启动之间的区别,您可以处理 WM_QUERYENDSESSION 消息。
“Windows Vista 的关机更改”是一篇了解关机的有用文章暂停。
To add to @Adam's answer, if you need to tell the difference between logoff and shutdown/reboot, you can handle the WM_QUERYENDSESSION message.
"Shutdown Changes for Windows Vista" is a useful article for understanding the shutdown timeout.
如今,试图阻止关闭是一个有损的提议,在 Vista 及更高版本中不再可能这样做。提示不可读也不可达。此处强烈指示使用服务,让您在用户注销后幸存下来。重新启动后,您的服务将自动重新开始运行,让您完成工作。
Trying to block a shutdown is a lossy proposition these days, it's no longer possible to do so in Vista and up. A prompt isn't readable nor reachable. Using a service is highly indicated here, lets you survive a user log-off. And a reboot, your service will start running again automatically, letting you complete the job.