Search code examples
android.netwindowsusbwinusb

How to get notified if a USB device of a specific interface is connected in Windows?


I would like to be informed, if a (Android) USB device of a specific interface (USB debugging) is connected to my Windows computer.

For this, I'm trying to use .Net with this code:

const string GUID_DEVINTERFACE_ANDROID = "f72fe0d4-cbcb-407d-8814-9ed673d0dd6b";
const string usbDeviceSelector = "System.Devices.InterfaceClassGuid:=\"{" + GUID_DEVINTERFACE_ANDROID + "}\" AND System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True";

_usbDeviceWatcher = DeviceInformation.CreateWatcher(
    usbDeviceSelector,
    new string[] { "System.Devices.InterfaceEnabled" },
    DeviceInformationKind.AssociationEndpoint);
_usbDeviceWatcher.Updated += UsbDeviceWatcher_Updated;

Unfortunately, the event will not be thrown to my UsbDeviceWatcher_Update function.

I don't want to be informed about a specific device, I want to be notified about all devices, which supports this interface.

How can I get an event, if an device with this special interface will be connected / disconnected from my computer?

If there is a WinUsb solution for this, I would be happy too.


Solution

  • Filter for the a USB device with the interface class {f72fe0d4-cbcb-407d-8814-9ed673d0dd6b} and then subscribe to the Added and Removed events:

    using Windows.Devices.Enumeration;
    using Windows.Devices.Usb;
    
    var filter = UsbDevice.GetDeviceSelector(new Guid("f72fe0d4-cbcb-407d-8814-9ed673d0dd6b"));
    var usbDeviceWatcher = DeviceInformation.CreateWatcher(filter);
    usbDeviceWatcher.Added += UsbDeviceWatcher_Added;
    usbDeviceWatcher.Removed += UsbDeviceWatcher_Removed;
    usbDeviceWatcher.Start();
    
    Console.WriteLine("Press key to exit...");
    Console.ReadKey();
    
    void UsbDeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args)
    {
        Console.WriteLine("Added");
    }
    
    void UsbDeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args)
    {
        Console.WriteLine("Removed");
    }
    

    Alternatively, you can also filter for interface class 0xff, subclass 0x42 and protocol 0x01:

    var filter = UsbDevice.GetDeviceClassSelector(new UsbDeviceClass() {
        ClassCode = 0xff,
        SubclassCode = 0x42,
        ProtocolCode = 0x01
    });
    

    You can also implement the approach proposed by David Grayson's. But it's considerably more effort.