#include <windows.h>
#include <setupapi.h>
#include <iostream>
#include <vector>
#include <string>
#include <devguid.h>
#include <cfgmgr32.h>
#pragma comment(lib, "setupapi.lib")
DWORD GetDeviceIndexByInstancePath(const std::wstring& deviceInstancePath) {
// 设定参数
DWORD deviceIndex = -1;
GUID* guid = (GUID*)&GUID_DEVCLASS_USB;
// 打开所有设备信息集合
HDEVINFO hDeviceInfoSet = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_PRESENT | DIGCF_ALLCLASSES);
//打开指定类
//HDEVINFO hDeviceInfoSet = SetupDiGetClassDevs(guid, NULL, NULL, DIGCF_PRESENT );
if (hDeviceInfoSet == INVALID_HANDLE_VALUE) {
return -1;
}
// 遍历设备信息集合
SP_DEVINFO_DATA deviceInfoData;
deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
deviceIndex = 0;
DWORD canIndex = -1;
while (SetupDiEnumDeviceInfo(hDeviceInfoSet, deviceIndex, &deviceInfoData)) {
DWORD dataSize = 0;
SetupDiGetDeviceRegistryProperty(hDeviceInfoSet, &deviceInfoData,
SPDRP_CLASS, NULL, NULL, 0, &dataSize);
TCHAR hardwareID[MAX_DEVICE_ID_LEN] = { 0 };
if (SetupDiGetDeviceRegistryProperty(hDeviceInfoSet, &deviceInfoData,
SPDRP_CLASS, NULL, (PBYTE)hardwareID, dataSize, &dataSize)) //获取指定设备类的属性
{
//找设备类
if (wcscmp(hardwareID, L"USB CAN") == 0) {
// 获取设备实例路径
WCHAR instancePath[MAX_DEVICE_ID_LEN] = { 0 };
if (SetupDiGetDeviceInstanceId(hDeviceInfoSet, &deviceInfoData, instancePath, MAX_DEVICE_ID_LEN, NULL)) {
std::wcout << instancePath << std::endl;
canIndex++;
if (wcscmp(instancePath, deviceInstancePath.c_str()) == 0) {
// 释放设备信息集合
SetupDiDestroyDeviceInfoList(hDeviceInfoSet);
return canIndex;
}
}
}
}
deviceIndex++;
}
// 清理并返回失败
SetupDiDestroyDeviceInfoList(hDeviceInfoSet);
return -1;
}
int main()
{
std::cout << "Hello World!\n";
std::wstring deviceInstancePath = L"USB\\VID_0C66&PID_000C\\152221071166";
DWORD index = GetDeviceIndexByInstancePath(deviceInstancePath);
if(-1 != index)
std::cout << "USB CAN Device Index: " << index << std::endl;
return 0;
}
windows 平台 C 获取设备管理器设备信息
最新推荐文章于 2025-03-10 20:17:27 发布