You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PortableDeviceApi时IPortableDeviceManager::GetDevices返回0设备求助

问题分析与解决

为什么IPortableDeviceManager::GetDevices返回0?

IPortableDeviceManager属于Windows Portable Device (WPD) API,它仅枚举支持WPD协议的便携设备,比如:

  • 开启MTP模式的智能手机、平板
  • 数码相机、摄像机
  • MP3播放器等便携式媒体设备

而PowerShell的Get-PnpDevice是枚举系统中所有即插即用设备,包含主板、显卡、键盘这类不支持WPD协议的硬件,两者枚举范围完全不同,所以结果差异是正常的。

枚举所有PnP设备的正确方案

要获取系统全部PnP设备,需使用Windows SetupAPI,这是专门用于设备枚举与配置的API,示例代码如下:

#include <iostream>
#include <windows.h>
#include <setupapi.h>
#include <initguid.h>
#include <devguid.h>

#pragma comment(lib, "setupapi.lib")

void getAllPnPDevices() {
    // 获取所有已连接的设备信息集合
    HDEVINFO hDevInfo = SetupDiGetClassDevs(&GUID_DEVCLASS_ALL, nullptr, nullptr, DIGCF_PRESENT | DIGCF_ALLCLASSES);
    if (hDevInfo == INVALID_HANDLE_VALUE) {
        std::cout << "SetupDiGetClassDevs failed, error: " << GetLastError() << std::endl;
        return;
    }

    SP_DEVINFO_DATA devInfoData = { 0 };
    devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);

    // 遍历每个设备
    for (DWORD i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &devInfoData); i++) {
        // 获取设备友好名称
        TCHAR deviceName[MAX_PATH] = { 0 };
        if (SetupDiGetDeviceRegistryProperty(hDevInfo, &devInfoData, SPDRP_FRIENDLYNAME, nullptr, (PBYTE)deviceName, sizeof(deviceName), nullptr)) {
            std::wcout << L"设备名称: " << deviceName << std::endl;
        }

        // 获取设备PNP ID
        TCHAR pnpId[MAX_PATH] = { 0 };
        if (SetupDiGetDeviceInstanceId(hDevInfo, &devInfoData, pnpId, sizeof(pnpId)/sizeof(TCHAR), nullptr)) {
            std::wcout << L"PNP ID: " << pnpId << std::endl;
        }

        std::wcout << L"-------------------------" << std::endl;
    }

    // 释放设备信息集合
    SetupDiDestroyDeviceInfoList(hDevInfo);
}

int main() {
    getAllPnPDevices();
    return 0;
}

补充说明

  • 编译时需链接setupapi.lib,示例代码已通过#pragma comment(lib, "setupapi.lib")自动处理
  • 若你确实需要枚举WPD设备,请确保目标设备已启用MTP/WPD模式(如安卓手机开启文件传输模式)并安装对应驱动

内容的提问来源于stack exchange,提问作者0xREDACTED

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 09:42:31