public static List <HidInfo> Browse() { Guid gHid; List <HidInfo> info = new List <HidInfo>(); // Obtain hid guid Native.HidD_GetHidGuid(out gHid); // Get list of present hid devices var hInfoSet = Native.SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, Native.DIGCF_DEVICEINTERFACE | Native.DIGCF_PRESENT); // Allocate mem for interface descriptor var iface = new Native.DeviceInterfaceData(); // Set size field iface.Size = Marshal.SizeOf(iface); // Interface index uint index = 0; // iterate through all interfaces while (Native.SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, index, ref iface)) { short vid, pid; var path = GetPath(hInfoSet, ref iface); var handle = Open(path); if (handle != Native.INVALID_HANDLE_VALUE) { var man = GetManufacturer(handle); var prod = GetProduct(handle); var serial = GetSerialNumber(handle); GetVidPid(handle, out vid, out pid); var cap = GetDeviceCapabilities(handle); HidInfo i = new HidInfo(prod, serial, man, path, vid, pid, cap); info.Add(i); Close(handle); } index++; } // Clean up if (Native.SetupDiDestroyDeviceInfoList(hInfoSet) == false) { throw new Win32Exception(); } return(info); }
public bool Open(HidInfo hidInfo) { Close(); SafeFileHandle shandle; // Open HID device file handle = Native.CreateFile(hidInfo.Path, Native.GENERIC_READ | Native.GENERIC_WRITE, Native.FILE_SHARE_READ | Native.FILE_SHARE_WRITE, IntPtr.Zero, Native.OPEN_EXISTING, Native.FILE_FLAG_OVERLAPPED, IntPtr.Zero); // Return failure if handle is invalid if (handle == Native.INVALID_HANDLE_VALUE) { return(false); } // Open safe file handle shandle = new SafeFileHandle(handle, false); // Prepare stream - async fileStream = new FileStream(shandle, FileAccess.ReadWrite, 32, true); // Start asyncronous receive task receiveQueue = new BlockingCollection <byte[]>(1000); if (receiveTask != null) { if (!receiveTask.IsCompleted) { throw new Exception("Task already running"); } } receiveTask = new Task(() => ReceiveTask(receiveQueue), TaskCreationOptions.LongRunning); receiveTask.Start(); hidDeviceState = HidDeviceState.Open; // Return success return(true); }