C# - How to detect a Windows shutdown/logoff and cancel that action (after asking the user)

纵饮孤独 提交于 2019-11-26 09:55:02

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/4617538/c-sharp-how-to-detect-a-windows-shutdown-logoff-and-cancel-that-action-after

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!