Resolved Detect Windows Shutdown/Logoff

JuggaloBrotha

VB.NET Forum Moderator
Staff member
Joined
Jun 3, 2004
Messages
4,530
Location
Lansing, MI; USA
Programming Experience
10+
I have an application that starts from Sub Main and I need to run a sub when the system is about to shut down, restart or logoff so it can save it's settings. I found some code on google:
VB.NET:
Imports Microsoft.Win32

    Public Sub Main
        AddHandler SystemEvents.SessionEnding, AddressOf OnShuttingdown
        'Rest of app, including the While Loop to do it's thing
    End Sub

    Public Sub OnShuttingdown(ByVal sender As Object, ByVal e As SessionEndingEventArgs)
        'Code that signal's app's exiting which in turn sets a variable that tells the While Loop to exit
    End Sub
But it doesn't seem to work, Windows shuts down yes but when I re-start the vm and run the app it opens with the old settings, not the ones that I changed before I shut down the vm. Anyone know of a way to do this or to fix the code above, I don't think my OnShuttingdown event is being handled.
 
If you have a look at the following article on my website, it shows the code that I used to do something similar.
VB.Net detect Windows shutting down or logging off - VB.Net Articles - SatalKeto.co.uk
You will need to add your code to save the settings to where the comment "'We allow the form to close" is.
What I've done looks pretty much the same as what you've done, but maybe the small difference will sort out your problem.

Hope this helps

Satal :D
 
Right, except that I don't have a form and the rest of it is the same code I already have in my project.

I did find out that the event I have in my code is being fired, the problem is that windows cuts it off before my app can close itself, so the settings never get saved. I need to look up how to request 30 seconds time from windows so it can close itself.

Also Satal, you don't need to be handling the SystemEvents.SessionEnding or anything like that in your example, in the form's FormClosing event, check e.CloseReason and unless it's a TaskManager or WindowsShutDown then just cancel (set e.Cancel = True) and the form will stay open. You can follow that line with your form hiding code, etc... too.
 

Latest posts

Back
Top