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

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


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.


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.


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.