Search code examples
windowswinapiusblibusb

Check if specific USB-device is available


I need to find out if a USB device with a special Vendor/Product ID is available (I only wat to check if it exists, no access is necessary). When using libusb-win32 this can be done only for these devices that have a libusb driver/filter driver installed which would not work in my case.

So...is there a possibility to enumerate all available USB-devices and to get their VID/PID? Any example codes available for that?

Thanks!


Solution

  • Yes, it is possible to archive it by WMI queries, for example to get SN of plugged USB pen drives (if they have it, some doesn't).

    Check WMI Win32_PNPEntity class or Win32_USBHub, Win32_USBControllerDevice classes.

    EDIT:

    For enumerating all devices, remove the WHERE clause:

    using System;
    using System.Management;
    using System.Windows.Forms;
    
    namespace WMISample
    {
        public class MyWMIQuery
        {
            public static void Main()
            {
                try
                {
                    ManagementObjectSearcher searcher = 
                        new ManagementObjectSearcher("root\\CIMV2", 
                        "SELECT * FROM Win32_PnPEntity WHERE DeviceID = 'USB\\VID_8087&PID_0024\\5&38CA7A24&0&1'"); 
    
                    foreach (ManagementObject queryObj in searcher.Get())
                    {
                        Console.WriteLine("-----------------------------------");
                        Console.WriteLine("Win32_PnPEntity instance");
                        Console.WriteLine("-----------------------------------");
                        Console.WriteLine("DeviceID: {0}", queryObj["DeviceID"]);
                    }
                }
                catch (ManagementException e)
                {
                    MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
                }
            }
        }
    }