void ReHIDUI() { if (HIDDevice.TheHIDDevice == null) { HIDDevice.TheHIDDevice = HIDDevice.FindDevice(); } HIDUI(); }
protected override void WndProc(ref Message m) { try { if (m.Msg == 0x0219) { switch (m.WParam.ToInt32()) { case 0x8000: if (HIDDevice.TheHIDDevice == null) { HIDDevice.TheHIDDevice = HIDDevice.FindDevice(); } HIDUI(); break; case 0x8004: try { HIDDevice.TheHIDDevice.Dispose(); HIDDevice.TheHIDDevice = null; } catch { } HIDUI(); break; default: break; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } base.WndProc(ref m); }
public static HIDDevice FindDevice() { string strPath = string.Empty; string strSearch = string.Format("vid_{0:x4}&pid_{1:x4}", VendorID, ProductID); // first, build the path search string string strSearch1 = string.Format("vid_{0:x4}&pid_{1:x4}", VendorID, ProductID_old); // first, build the path search string Guid gHid; HidD_GetHidGuid(out gHid); // next, get the GUID from Windows that it uses to represent the HID USB interface IntPtr hInfoSet = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT); // this gets a list of all HID devices currently connected to the computer (InfoSet) try { DeviceInterfaceData oInterface = new DeviceInterfaceData(); // build up a device interface data block oInterface.Size = Marshal.SizeOf(oInterface); // Now iterate through the InfoSet memory block assigned within Windows in the call to SetupDiGetClassDevs // to get device details for each device connected int nIndex = 0; while (SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, (uint)nIndex, ref oInterface)) // this gets the device interface information for a device at index 'nIndex' in the memory block { string strDevicePath = GetDevicePath(hInfoSet, ref oInterface); // get the device path (see helper method 'GetDevicePath') if (strDevicePath.IndexOf(strSearch) >= 0 || strDevicePath.IndexOf(strSearch1) >= 0) // do a string search, if we find the VID/PID string then we found our device! { HIDDevice oNewDevice = null; try { int retry = 3; while (retry != 0) { //Thread.Sleep(3000); oNewDevice = new HIDDevice(); // create an instance of the class for this device oNewDevice.Initialise(strDevicePath); // initialise it with the device path if (oNewDevice.CheckDevice()) { return(oNewDevice); // and return it } else { oNewDevice.Dispose(); oNewDevice = null; } retry--; } } catch { if (oNewDevice != null) { oNewDevice.Dispose(); oNewDevice = null; } } } nIndex++; // if we get here, we didn't find our device. So move on to the next one. } } finally { // Before we go, we have to free up the InfoSet memory reserved by SetupDiGetClassDevs SetupDiDestroyDeviceInfoList(hInfoSet); } return(null); // oops, didn't find our device }