Had a tricky problem today whilst working on my wallpaper application.
The program resides in the tray and has a settings form that I don't want to really quit the application when closed, just hide the window and still sit in the tray. The trouble was I wanted to respond to windows shut down requests and actually quit the application, without the following fix my application cancelled the windows shutdown!
After much searching I came across the handy WM_QueryEndSession message. The code snippet below shows it's use for detecting a true windows shut down rather than just a close of the form.
Private Shared WM_QUERYENDSESSION As Integer = &H11
Private Shared systemShutdown As Boolean = False
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
If m.Msg = WM_QUERYENDSESSION Then
systemShutdown = True
End If
' If this is WM_QUERYENDSESSION, the closing event should be fired in the base WndProc
MyBase.WndProc(m)
End Sub 'WndProc
Private Sub frmMain_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
If Not systemShutdown Then
Me.Visible = False
e.Cancel = True
Else
e.Cancel = False
End If
End Sub