How can I put some processing that will execute when the OS is shutdown

Hitoruna

Member
Joined
Sep 12, 2017
Messages
11
Programming Experience
5-10
First my question:

How can I put some code that will be executed when the OS is shutdown?

----

Then what I have done:
I read about SessionEnding, if I add an event handler to
C#:
SystemEvents.SessionEnding
I can do that.
I found this in https://books.google.co.jp/books?id...MAc#v=onepage&q=SessionEnding example&f=false

C# Cookbook page 772

However, how can I debug a program through a shutdown?? I tried and visual studio failed with the message
"A process used by visual studio has encountered an unrecoverable error, we recommend saving your work and then closing and restarting visual studio"

Any help will be greatly appreciated
 
You may not be able to debug it. I would guess that the OS would send a message to each application telling them that a shutdown has been requested and they would need to respond within a specified time period to prevent it or else the shutdown would go ahead. You might need to add some tracing code and write the application state to a file in order to see what's happening as your code is executed.
 
I have used SystemEvents.SessionEnding to detect when the system is shutting down but learned quickly that your app only has maybe 45 seconds to complete whatever processing you need to do before Win7 & newer will terminate it anyways which I was able to use to save to the app's config file.

You can also use the Microsoft.Win32.SystemEvents.SessionSwitch which gives you the Microsoft.Win32.SessionSwitchEventArgs as the 'e' variable where you have e.Reason that you can check for things like SessionLogoff, SessionLogon, SessionLock, SessionUnlock, etc to do various things.

One thing to realize is for all of these you wont be able to actually debug in VS as most of the time VS is closing down as well so you will have to write things to a log file and trace your logic that way.
 
Back
Top Bottom