Detect when Windows is shutting down

  • Thread starter Thread starter Mike Stephens
  • Start date Start date
M

Mike Stephens

I have an application to minimizes when X is clicked. If the user wants to
close the application they click the Exit Application button.This works fine
and does exactly what I need. I have since discovered it is holding Windows
open when you shutdown. If the application is running and the user
shutsdown Window it holds up everything. If the application is not running
and the user shutsdown Windows is shutsdown in a timely manner.

How can I detect when Windows is shutting down and have the application
close itself?

Regards,
Mike.
 
Hi Mike,

.NET has just the thing for you. :-)

It's incredibly simple but it took a bit of a hunt finding out how to use
it. the MSDN documentation is almost meaningless :-(

I found this site very useful:
http://www.codeworks.it/net/Sysevents.htm

In the Microsoft.Win32 namespace there are a set of SystemEvents two of
which cover System Shutdown - SessionEnding and SessionEnded. The first is a
request and you you have the option of cancelling the request. The second is a
command.

To react to these events, put
AddHandler (SystemEvents.SessionEnding, AddressOf
ShutDown.OnShuttingDown)
AddHandler (SystemEvents.SessionEnded, AddressOf ShutDown.OnShutDown)
somewhere in your initialisation code.

Put the following class somewhere

Public Class Shutdown
Public Shared Sub OnShuttingdown (sender As Object, e As
SessionEndingEventArgs)
e.Cancel = True 'True if you are turning down the request to
shutdown. Otherwise leave.
Console.WriteLine ("Shutting down - Reason is " & e.Reason)
'Shut down your Application here or...
End Sub

Public Shared Sub OnShutdown (sender As Object, e As
SessionEndedEventArgs)
Console.WriteLine ("Shutdown - Reason is " & e.Reason)
'or...Shut down your Application here.
End Sub
End Class

Note. I haven't tested this. - too much hassle. Come back if you need any
more help with it.

Regards
Fergus
 
Back
Top