/// <summary> /// Detect the USBs. /// </summary> /// <param name="sender"></param> private void DetectUSBMethod(object sender) { USBs.Clear(); try { // Find in Win32_PnPEntity id that contains USBs. ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEntity WHERE PnPClass='USB'"); foreach (ManagementObject queryObj in searcher.Get()) { if (queryObj["Name"] == null) { // skip } else if (!USBs.Contains(queryObj["Name"].ToString())) { if (!(queryObj["Name"].ToString().Contains("Composite")) && !(queryObj["Name"].ToString().Contains(" Hub"))) // these are USB supporting device, not USB { if (IsPluggedInUSB(queryObj["DeviceID"].ToString())) { USBs.Add(queryObj["Name"].ToString()); } } } } } catch (ManagementException e) { MessageBox.Show("An error occurred while querying for WMI data: " + e.Message); } }
/// <summary> /// Display message about the device inserted. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DeviceInsertedEvent(object sender, EventArrivedEventArgs e) { ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"]; string name = instance.Properties["Name"].Value.ToString(); string output = name + " is Inserted."; App.Current.Dispatcher.Invoke((Action) delegate // Trigger action in the UI thread { if (IsOfUSBType(instance.Properties["DeviceID"].Value.ToString())) { USBs.Add(name); } else { VCPs.Add(name); } Statuses.Add(output); }); }