How to Detect Whether Windows Is Shutting Down or Restarting

How to detect whether Windows is shutting down or restarting

From here:

You can read the DWORD value from
"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shutdown
Setting" to determine what the user
last selected from the Shut Down
dialog.

A bit of a roundabout solution, but it should do the trick.

Is there a way to programmatically receive if Windows is shutting down or restarting?

There is a way to detect whether it is shutting down and also there is a way to detect when it starts up.

So, you can note the time when it is shutting down. Note the time when it is starting by running an exe at startup (add your exe here in registry: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce).

If the time difference is very less then you can treat it as a 'Restart'.

Also you can use WTSRegisterSessionNotification api for exact events.

How to tell if a Windows server is in the act of shutting down

Your best bet would be to query the system event log. If someone runs the shutdown command, an event gets logged. I am sure if you have something else initiating the shutdown that there will be event logs indicating that it is going down.

Get-EventLog system -Newest 20 -Source User32

Running this on my machine lists several shutdown events from different processes.

The process C:\WINDOWS\system32\winlogon.exe (computername) has initiated the 
restart of computer COMPUTERNAME on behalf of user KEVMAR for the following
reason: No title for this reason could be found

This would be a good starting point.

A trick I use is to just run Shutdown /a and it will tell me if it stopped a shutdown.

How to detect Windows shutdown or logoff

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.



Related Topics



Leave a reply



Submit