/// <summary> /// 获取HID设备列表 /// </summary> private void GetHidDeviceList() { // 获取HID设备列表 List <string> deviceList = HidAPI.GetHidDeviceList(); DebugPrint($"[遍历HID设备列表] 找到 {deviceList.Count} 个HID标准设备"); // 对列表排序 deviceList.Sort(); // 筛选符合要求的设备 deviceList = deviceList.Select(s => s.ToUpper()).Where(str => str.Contains("VID_2333")).ToList(); DebugPrint($"[筛选HID设备列表] 找到 {deviceList.Count} 个符合要求的设备"); // 筛选新添加的设备 if (HidDevice != null) { deviceList = deviceList.Where(str => !HidDevice.Exists(dev => dev.Path == str)).ToList(); } DebugPrint($"[筛选HID设备列表] 找到 {deviceList.Count} 个刚添加的新设备"); // 连接新添加的设备 if (deviceList.Count > 0) { DeviceList.ItemsSource = deviceList; DeviceList.SelectedIndex = 0; ConnectDevice(deviceList); } else { DeviceList.ItemsSource = null; } }
/// <summary> /// 连接HID设备 /// </summary> /// <param name="devicePath">目标设备地址</param> private void ConnectDevice(List <string> deviceList) { deviceList.ForEach(devicePath => { DebugPrint($"<连接设备> {devicePath}"); // 使用共享模式打开设备读写句柄 IntPtr devHandle = WinAPI.CreateFile(devicePath.ToLower(), WinAPI.Generic.READ | WinAPI.Generic.WRITE, (uint)FileShare.ReadWrite, 0, WinAPI.CreationDisposition.OPEN_EXISTING, WinAPI.FileFlag.OVERLAPPED, 0); // 若打开设备句柄失败则返回失败标志 if (devHandle == new IntPtr(-1)) { DebugPrint($"<连接设备失败> {devicePath.ToUpper()}"); DebugPrint($"<GetLastError()={WinAPI.GetLastError()}> {WinAPI.ErrorCode(WinAPI.GetLastError())}"); return; } // 获取设备属性 (若不需要可删除) HidAPI.HidD_GetAttributes(devHandle, out HidAPI.HidAttributes devAttr); // 找到对应的HID设备信息 HidAPI.HidD_GetPreparsedData(devHandle, out IntPtr preparseData); HidAPI.HidP_GetCaps(preparseData, out HidAPI.HIDP_CAPS devCaps); HidAPI.HidD_FreePreparsedData(preparseData); // 创建设备读写通道 HidDevice.Add(new USBDevice() { Path = devicePath, Attr = devAttr, Caps = devCaps, Channel = new FileStream(new SafeFileHandle(devHandle, false), FileAccess.ReadWrite, devCaps.InputLength, true) }); }); if (HidDevice.Count > 0) { HidDevice.ForEach(dev => { DebugPrint($"设备已连接-> {dev.Path}"); UsbReadAsync(dev); // 开始异步读取设备数据 }); // 通知设备已连接 OnDeviceConnected(HidDevice[0].Attr.PID); } }