windows 平台 C 获取设备管理器设备信息

#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;
}

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值