title: VB.NET/WMI - Real-Time Windows Service Monitoring?
body: <p>So there's an application at my work that installs several Windows services to a server.  As a side project, I've been asked to make a simple GUI that will list these services with a "light" (a picture box with a red or green dot) next to the name of each service.  The idea is that in the event these services were to stop running, the "light" would change from green to red.</p>
  
  <p>I have the GUI part built, and I can query a remote server's services, then compare it to an array of the ones I'm interested and set the "light" next to each service to green/red depending on the service state.  The part I'm hung up on is how to monitor these services in real time?  Currently, I just have the following code in the Form_Load event:</p>
  
  <pre><code>Dim myConnectionOptions As New System.Management.ConnectionOptions
  With myConnectionOptions
      .Impersonation = System.Management.ImpersonationLevel.Impersonate
      .Authentication = System.Management.AuthenticationLevel.Packet
  End With
  
  Try
  
      Dim myManagementScope As System.Management.ManagementScope
      myManagementScope = New System.Management.ManagementScope("\\" &amp; SERVERNAME &amp; "\root\cimv2", myConnectionOptions)
      myManagementScope.Connect()
  
      Dim query As New Management.ObjectQuery("SELECT * FROM Win32_Service")
      Dim searcher As New Management.ManagementObjectSearcher(myManagementScope, query)
      Dim i As Integer = 0
  
      For Each queryObj As Management.ManagementObject In searcher.Get()
          For Each service As String In arrServices
              If queryObj("DisplayName").Equals(service) Then
                  If queryObj("State").Equals("Stopped") Then
                      arrLights(i).Image = My.Resources.redlight
                  End If
                  i += 1
              End If
          Next
      Next
  
  Catch err As Management.ManagementException
      MessageBox.Show("WMI query failed with the following error: " &amp; err.Message)
  Catch unauthorizedErr As System.UnauthorizedAccessException
      MessageBox.Show("Authentication error: " &amp; unauthorizedErr.Message)
  End Try
  </code></pre>
  
  <p>Would a simple timer that executes this code repeatedly be the best approach, or is there a more elegant solution? I have a little experience in VB.NET and WMI, but none in any type of real-time monitoring activity like this.</p>