以下是一个使用 C++ 在 Windows 上搜索 USB 设备的示例代码:
#include <Windows.h>
#include <SetupAPI.h>
#include <iostream>
#pragma comment(lib, "setupapi.lib")
int main() {
// 初始化设备信息列表
HDEVINFO deviceInfoSet = SetupDiGetClassDevs(NULL, TEXT("USB"), NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (deviceInfoSet == INVALID_HANDLE_VALUE) {
std::cout << "Failed to get device information set." << std::endl;
return 1;
}
SP_DEVINFO_DATA deviceInfoData;
ZeroMemory(&deviceInfoData, sizeof(SP_DEVINFO_DATA));
deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
// 遍历设备信息列表
for (DWORD i = 0; SetupDiEnumDeviceInfo(deviceInfoSet, i, &deviceInfoData); ++i) {
TCHAR deviceID[MAX_DEVICE_ID_LEN];
if (CM_Get_Device_ID(deviceInfoData.DevInst, deviceID, MAX_PATH, 0) != CR_SUCCESS) {
continue;
}
// 判断是否为 USB 设备
DWORD capabilities;
CM_Get_DevNode_Registry_Property(deviceInfoData.DevInst,
CM_DRP_CAPABILITIES,
NULL,
reinterpret_cast<PBYTE>(&capabilities),
sizeof(capabilities),
0);
if (!(capabilities & CM_DEVCAP_REMOVABLE)) {
continue;
}
// 打印设备信息
TCHAR friendlyName[MAX_PATH];
TCHAR manufacturer[MAX_PATH];
TCHAR description[MAX_PATH];
if (SetupDiGetDeviceRegistryProperty(deviceInfoSet,
&deviceInfoData,
SPDRP_FRIENDLYNAME,
NULL,
reinterpret_cast<PBYTE>(friendlyName),
sizeof(friendlyName),
NULL)) {
std::wcout << "Friendly Name: " << friendlyName << std::endl;
}
if (SetupDiGetDeviceRegistryProperty(deviceInfoSet,
&deviceInfoData,
SPDRP_MFG,
NULL,
reinterpret_cast<PBYTE>(manufacturer),
sizeof(manufacturer),
NULL)) {
std::wcout << "Manufacturer: " << manufacturer << std::endl;
}
if (SetupDiGetDeviceRegistryProperty(deviceInfoSet,
&deviceInfoData,
SPDRP_DEVICEDESC,
NULL,
reinterpret_cast<PBYTE>(description),
sizeof(description),
NULL)) {
std::wcout << "Description: " << description << std::endl;
}
}
// 释放设备信息列表
SetupDiDestroyDeviceInfoList(deviceInfoSet);
return 0;
}
请注意,此代码使用了 Windows API 函数和结构体,并且需要链接 setupapi.lib 库。建议在 Visual Studio 等开发环境中进行编译和运行。
内容由零声教学AI助手提供,问题来源于学员提问




