private IntPtr OpenDFUDevice() { Guid GUID = GUID_DFU; DeviceInterfaceData ifData = new DeviceInterfaceData(); ifData.Size = Marshal.SizeOf(ifData); DeviceInterfaceDetailData ifDetail = new DeviceInterfaceDetailData(); UInt32 Size = 0; IntPtr hInfoSet = SetupDiGetClassDevs(ref GUID, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT); // this gets a list of all DFU devices currently connected to the computer (InfoSet) IntPtr hDevice = IntPtr.Zero; if (hInfoSet == INVALID_HANDLE_VALUE) { throw new Exception("Could not open DFU device!"); //throw new Exception("SetupDiGetClassDevs returned error=" + Marshal.GetLastWin32Error().ToString()); } // Loop ten times hoping to find exactly one DFU device int i = 10; uint Index = 0; while (i-- > 0) { Index = 0; while (SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref GUID, Index, ref ifData)) { Index++; } if (0 == Index) { Thread.Sleep(500); } else { break; } } if (1 == Index) { SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref GUID, 0, ref ifData); SetupDiGetDeviceInterfaceDetail(hInfoSet, ref ifData, IntPtr.Zero, 0, ref Size, IntPtr.Zero); if (IntPtr.Size == 8) // If we are compiled as 64bit { ifDetail.Size = 8; } else if (IntPtr.Size == 4) // If we are compiled as 32 bit { ifDetail.Size = 5; } if (Marshal.SizeOf(ifDetail) < Size) { throw new Exception("Could not open DFU device!"); //throw new Exception("ifDetail too small"); } if (true == SetupDiGetDeviceInterfaceDetail(hInfoSet, ref ifData, ref ifDetail, Size, ref Size, IntPtr.Zero)) { string DevicePath = ifDetail.DevicePath.ToUpper(); if (STDFU.STDFU_Open(DevicePath, out hDevice) != STDFU.STDFU_NOERROR) { throw new Exception("Could not open DFU device!"); } } } else { throw new Exception("There must be exactly one DFU device attached to the computer!"); } SetupDiDestroyDeviceInfoList(hInfoSet); return(hDevice); }