VB.NET • Set Tray Icon Properties

Listing 2. You keep track of the current state of the NotifyIcon with a Static variable in the SetNotifyIcon routine. When the file monitoring state changes, set the icon matching the new state from the ImageList. You accomplish this by creating a BitMap object from the desired ImageList icon. Use the BitMap's hIcon property to pass a "handle" to the icon to an Icon object's FromHandle method and assign this new icon to NotifyIcon's Icon property.

Private Sub SetNotifyIcon _
   (ByVal CurrentState As MonitorState, _
   ByVal Text As String)
   Static LastMonitorState As MonitorState = _
      MonitorState.msStartup
   If CurrentState <> LastMonitorState Then
      LastMonitorState = CurrentState
      Select Case CurrentState
         Case MonitorState.msNotMonitoring
            Dim bm As _
               System.Drawing.Bitmap = _
               ImageList1.Images(0)
            NotifyIcon1.Icon = _
               Icon.FromHandle(bm.GetHicon())
         Case MonitorState.msMonitoring
            Dim bm As System.Drawing.Bitmap = _
               ImageList1.Images(1)
            NotifyIcon1.Icon = _
               Icon.FromHandle(bm.GetHicon())
         Case MonitorState.msFileChanged
            Dim bm As System.Drawing.Bitmap = _
               ImageList1.Images(2)
            NotifyIcon1.Icon = _
               Icon.FromHandle(bm.GetHicon())
      End Select
   End If
   NotifyIcon1.Text = Text
   StatusBar1.Text = Text
End Sub