'How to Prevent System from Shutting down or Restart in a Win32 service?

I want to prevent users from shut down or restart the system. my application runs as a Win32 Native Service (written by C++) and under LocalSystem account.

I heard about WM_QUERYENDSESSION it's solution: creating a hidden window and capturing WM_QUERYENDSESSION to prevent shutdown.

but this solution is not really clean and also have to create one window for each desktop. So i have to enumerate desktops and also care about when a desktop created/destroyed. All of these make the situation nasty!

Is there any way to detect shutdown/restart event and prevent system shutdown/restart?

(It is not important that the event is shutdown or restart, both of them must be cancelled!)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source