Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect Windows shutdown or logoff

I need to detect when Windows is shutdown (or restarted) or when the user is logging off. I need to properly close the application before the application is closed. I noticed that no exit application event is raised when Windows is closing day.

I read the post Is there a way in c# to detect a Windows shutdown/logoff and cancel that action (after asking the user)

but I'm not sure of where I should perform the operations before closing. Thanks.

like image 590
Andrea Nagar Avatar asked Jul 23 '11 10:07

Andrea Nagar


People also ask

How do you diagnose an unexpected shutdown?

1] Through Event Viewer To find the cause of the unexpected shutdown using Event Viewer, use the following suggestions: Click on Start, type Event Viewer, and then select the result from the top of the list. After heading into Event Viewer, expand Windows Logs from the left and then select System.

How do I find out reason for shutdown?

Press the Windows + R keys to open the Run dialog, type eventvwr. msc, and press Enter. In the left pane of Event Viewer, double click/tap on Windows Logs to expand it, click on System to select it, then right click on System, and click/tap on Filter Current Log.


1 Answers

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.

like image 179
Cody Gray Avatar answered Sep 19 '22 15:09

Cody Gray