0

I'm using C# in Visual Studio and I want to detect if a specific USB device has been plugged in. I want to have a part of my program where I can allow the user to view all plugged in devices, and select their device which will 'Save' a unique property of the device, so that when a device is plugged in, the code can check if this device is the one saved.

So far I have a code which will detect when any USB is inserted and show a message box, and I also have a section of code that finds all the plugged in USB devices and can return their properties.

I now need to be able to determine the properties of the newly plugged in device (instead of just showing a message box) so I can check the properties. Also I am not sure which property of the USB device would be best to use a unique identifier.

Thank you for any help.

Code to detect inserted memory stick:

Using System.Management;

public Form1()
{
    InitializeComponent();            
    ManagementEventWatcher usbWatcher = new ManagementEventWatcher(queryString);          
    usbWatcher.EventArrived += new EventArrivedEventHandler(OnCreation);
    usbWatcher.Start();
}

public static string queryString = 
@"SELECT * 
FROM __InstanceOperationEvent
WITHIN 1
WHERE 
TargetInstance ISA 'Win32_USBHub'";


 private void OnCreation(object sender, EventArrivedEventArgs e)
 {
     MessageBox.Show("Memory Stick detected.");
 }

Code to find connected devices:

static List<USBDeviceInfo> GetUSBDevices()
{
      List<USBDeviceInfo> devices = new List<USBDeviceInfo>();

      var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub");

      foreach (var device in searcher.Get())
      {
          devices.Add(new USBDeviceInfo(
          (string)device.GetPropertyValue("DeviceID"),
          (string)device.GetPropertyValue("PNPDeviceID"),
          (string)device.GetPropertyValue("Description"),
          (string)device.GetPropertyValue("Name")
          ));
      }

      return devices;
}

  class USBDeviceInfo
  {
      public USBDeviceInfo(string deviceID, string pnpDeviceID, string description, string name)
      {
          this.DeviceID = deviceID;
          this.PnpDeviceID = pnpDeviceID;
          this.Description = description;
          this.Name = name;
      }
      public string DeviceID { get; private set; }
      public string PnpDeviceID { get; private set; }
      public string Description { get; private set; }
      public string Name { get; private set; }

  }

  public void usbSearch()
  {
      var usbDevices = GetUSBDevices();

      foreach (var usbDevice in usbDevices)
      {
           MessageBox.Show(usbDevice.DeviceID + "  " + usbDevice.PnpDeviceID + "  " + usbDevice.Description);
      }
  }
Aaron
  • 1
  • 1

0 Answers0