private void EnumerateDevices() { if (devices.Count > 0) { foreach (HidDevice dev in devices.Values) { dev.Dispose(); } } devices.Clear(); // Platform Device Enumeration int index = 0; NativeApi.SP_DEVICE_INTERFACE_DATA DeviceInterfaceData; using (DeviceInfoHandle DeviceHandle = NativeApi.SetupDiGetClassDevs(ref HidGuid, null, 0, NativeApi.DIGCF_DEVICEINTERFACE | NativeApi.DIGCF_PRESENT)) { DeviceInterfaceData = new NativeApi.SP_DEVICE_INTERFACE_DATA(); DeviceInterfaceData.cbSize = Marshal.SizeOf(DeviceInterfaceData); while (NativeApi.SetupDiEnumDeviceInterfaces(DeviceHandle, 0, ref HidGuid, index++, ref DeviceInterfaceData)) { string devPath = GetInterfacePath(ref DeviceInterfaceData, DeviceHandle); AddDeviceToList(devPath); } } }
private string GetInterfacePath(ref NativeApi.SP_DEVICE_INTERFACE_DATA DeviceInterfaceData, DeviceInfoHandle DeviceHandle) { int requiredSize = 0; NativeApi.SetupDiGetDeviceInterfaceDetail(DeviceHandle, ref DeviceInterfaceData, IntPtr.Zero, 0, ref requiredSize, IntPtr.Zero); IntPtr DetailDataBuffer = Marshal.AllocHGlobal(requiredSize); Marshal.WriteInt32(DetailDataBuffer, 4 + Marshal.SystemDefaultCharSize); NativeApi.SetupDiGetDeviceInterfaceDetail(DeviceHandle, ref DeviceInterfaceData, DetailDataBuffer, requiredSize, ref requiredSize, IntPtr.Zero); IntPtr pDevPath = new IntPtr(DetailDataBuffer.ToInt32() + 4); String devPath = Marshal.PtrToStringAuto(pDevPath); Marshal.FreeHGlobal(DetailDataBuffer); return(devPath); }