title: VB 6.0 system tray application doesn't close gracefully when Windows shuts down
body: <p>I'm using the following code within a VB 6.0 application to allow give the application a system tray icon:</p>
  
  <pre><code>Option Explicit
  
  'user defined type required by Shell_NotifyIcon API call
  Public Type NOTIFYICONDATA
     cbSize As Long
     hwnd As Long
     uId As Long
     uFlags As Long
     uCallBackMessage As Long
     hIcon As Long
     szTip As String * 64
  End Type
  
  'constants required by Shell_NotifyIcon API call:
  Public Const NIM_ADD = &amp;H0
  Public Const NIM_MODIFY = &amp;H1
  Public Const NIM_DELETE = &amp;H2
  Public Const NIF_MESSAGE = &amp;H1
  Public Const NIF_ICON = &amp;H2
  Public Const NIF_TIP = &amp;H4
  Public Const WM_MOUSEMOVE = &amp;H200
  Public Const WM_LBUTTONDOWN = &amp;H201     'Button down
  Public Const WM_LBUTTONUP = &amp;H202       'Button up
  Public Const WM_LBUTTONDBLCLK = &amp;H203   'Double-click
  Public Const WM_RBUTTONDOWN = &amp;H204     'Button down
  Public Const WM_RBUTTONUP = &amp;H205       'Button up
  Public Const WM_RBUTTONDBLCLK = &amp;H206   'Double-click
  
  Public Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long
  Public Declare Function Shell_NotifyIcon Lib "shell32" Alias "Shell_NotifyIconA" (ByVal dwMessage As Long, pnid As NOTIFYICONDATA) As Boolean
  
  Public nid As NOTIFYICONDATA
  </code></pre>
  
  <p>I want the application to minimize to the system tray when you click the Window's X to close it.  I accomplish this with the following code in the form's QueryUnload event:</p>
  
  <pre><code>Me.WindowState = vbMinimized
  Me.Hide
  </code></pre>
  
  <p>In the form's Unload event I do the following:</p>
  
  <pre><code>Shell_NotifyIcon NIM_DELETE, nid
  </code></pre>
  
  <p>The PROBLEM is that when I shut down the operating system and Windows sends the WM_CLOSE message to the app, QueryUnload is being fired but apparently not the Unload event, since Windows prompts me that it wants to end my task.  </p>
  
  <p>Any ideas on how to get the application to close gracefully on Windows shutdown?</p>
  
  <p>Thanks</p>