win10 通过PID和VID,枚举USB设备,然后打开,读写,最后关闭设备。
时间: 2024-05-16 20:13:56 浏览: 181
可以使用Windows API函数来实现。以下是一个简单的示例代码:
```c++
#include <Windows.h>
#include <cstdio>
int main()
{
// 枚举USB设备
GUID guid;
HDEVINFO hDevInfo;
SP_DEVICE_INTERFACE_DATA devInterfaceData;
SP_DEVINFO_DATA devInfoData;
DWORD dwSize, dwType, dwMemberIndex = 0;
char szDeviceInstanceID[MAX_DEVICE_ID_LEN];
ZeroMemory(&guid, sizeof(GUID));
guid = GUID_DEVINTERFACE_USB_DEVICE;
hDevInfo = SetupDiGetClassDevs(&guid, NULL, NULL, DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
if (hDevInfo == INVALID_HANDLE_VALUE) {
printf("SetupDiGetClassDevs failed (%d)\n", GetLastError());
return 1;
}
devInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
while (SetupDiEnumDeviceInterfaces(hDevInfo, NULL, &guid, dwMemberIndex, &devInterfaceData)) {
devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
if (SetupDiGetDeviceInterfaceDetail(hDevInfo, &devInterfaceData, NULL, 0, &dwSize, NULL)) {
PSP_DEVICE_INTERFACE_DETAIL_DATA pInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)LocalAlloc(LPTR, dwSize);
if (pInterfaceDetailData) {
pInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
if (SetupDiGetDeviceInterfaceDetail(hDevInfo, &devInterfaceData, pInterfaceDetailData, dwSize, NULL, &devInfoData)) {
if (SetupDiGetDeviceInstanceId(hDevInfo, &devInfoData, szDeviceInstanceID, MAX_DEVICE_ID_LEN, NULL)) {
// 打开设备
HANDLE hDevice = CreateFile(szDeviceInstanceID, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (hDevice != INVALID_HANDLE_VALUE) {
// 读写操作
DWORD dwBytesWritten;
BYTE buffer[256];
if (WriteFile(hDevice, buffer, sizeof(buffer), &dwBytesWritten, NULL)) {
// 写操作成功
}
DWORD dwBytesRead;
if (ReadFile(hDevice, buffer, sizeof(buffer), &dwBytesRead, NULL)) {
// 读操作成功
}
// 关闭设备
CloseHandle(hDevice);
}
}
}
LocalFree(pInterfaceDetailData);
}
}
dwMemberIndex++;
}
SetupDiDestroyDeviceInfoList(hDevInfo);
return 0;
}
```
需要注意的是,使用该代码需要管理员权限。另外,代码仅用于演示如何枚举、打开、读写、关闭USB设备,实际应用时需要根据具体情况进行改写和完善。
阅读全文