title: Using WMI to identify which device caused a Win32_DeviceChangeEvent
body: <p>I have been writing some code that detects add and removal of USB devices, and I've used the following WMI code to register for device change notifications:</p>
  
  <pre><code>watcher = new ManagementEventWatcher(query);
  watcher.EventArrived += new EventArrivedEventHandler(DeviceChangeEventReceived);
  watcher.Start();
  </code></pre>
  
  <p>This is the handler code:</p>
  
  <pre><code>void DeviceChangeEventReceived(object sender, EventArrivedEventArgs e)
  {
     foreach (PropertyData pd in e.NewEvent.Properties)
     {
        Log.Debug("\t" + pd.Name + ":" + pd.Value + "\t" + pd.Value.GetType());
     }
  }
  </code></pre>
  
  <p>This is great and all, it works for any USB device I plug in or remove from the system.  The problem that I'm having is, how do I identify the the device specifically that caused the events?  </p>
  
  <p>Elsewhere in my program, I'm keeping a list of currently connected devices that I'm most interested in, so if a device-removed event comes through, I can check that list against WMI using "select * from Win32_PnPEntity" or some other similar query.  BUT, this is a very inaccurate and cumbersome way of identifying the device that was removed.  The added problem is, I have no way of accurately telling what device was added, unless I cache the entire list of Win32_PnPEntity ahead of time, and do really crazy comparisons/validations.</p>
  
  <p>Am I missing something obvious here?  How do I associate the device change events to a specific device?</p>
  
  <p>UPDATE:  I still haven't come up with an ideal solution to this problem, but what I am doing is maintaining a list of currently connected devices (that I'm interested in) in memory, and every time an event is handled (see above), I query the Win32_PnPEntity to see if the devices I have stored in my connected device list are still connected.  This is a sub-optimal solution, because it just seems weird that I can't get any specific device identification information from the event that indicates "device change event".  Seems VERY strange, that this info is unavailable.   <em>sigh</em></p>