枚举设备 (WPD)

大多数应用程序完成的第一个任务是枚举连接到计算机的设备。 IPortableDeviceManager 接口支持此任务以及检索设备信息 (,例如制造商、友好名称和说明) 。

DeviceEnumeration.cpp 模块中的 EnumerateAllDevices 函数包含的代码演示已连接设备计数的检索,以及检索计数后检索每个已连接设备的特定于设备的信息的代码。

EnumerateAllDevices 函数完成四个主要任务:

  1. 创建可移植设备管理器对象。
  2. 检索连接的设备的计数。
  3. 检索已连接设备) 的设备信息 (。
  4. 释放检索设备信息时使用的内存。

以下各节将更详细地介绍这四个任务中的每一个。

设备枚举过程的第一步是创建可移植设备管理器对象。 为此,调用 CoCreateInstance 函数并将类标识符传递给对象的 CLSID) (,指定运行代码的上下文,指定 IPortableDeviceManager 接口的引用标识符,然后提供接收 IPortableDeviceManager 接口指针的指针变量。

HRESULT hr = CoCreateInstance(CLSID_PortableDeviceManager,
                              NULL,
                              CLSCTX_INPROC_SERVER,
                              IID_PPV_ARGS(&pPortableDeviceManager));
if (FAILED(hr))
{
    printf("! Failed to CoCreateInstance CLSID_PortableDeviceManager, hr = 0x%lx\n",hr);
}

获取 IPortableDeviceManager 接口指针后,可以开始在此接口上调用方法。 EnumerateAllDevices 函数中调用的第一个方法是 IPortableDeviceManager::GetDevices。 当调用此方法时,第一个参数设置为 NULL 时,它将返回连接的设备的计数。

if (SUCCEEDED(hr))
{
    hr = pPortableDeviceManager->GetDevices(NULL, &cPnPDeviceIDs);
    if (FAILED(hr))
    {
        printf("! Failed to get number of devices on the system, hr = 0x%lx\n",hr);
    }
}

// Report the number of devices found.  NOTE: we will report 0, if an error
// occured.

printf("\n%d Windows Portable Device(s) found on the system\n\n", cPnPDeviceIDs);

检索已连接设备的计数后,可以使用此值检索每个已连接设备的设备信息。 此过程首先将字符串指针数组作为第一个参数传递,并将此数组可以保留为第二个参数的元素数计数, (此计数至少应等于) 的可用设备数。

此方法返回的字符串是连接的设备的即插即用名称。 反过来,这些名称将传递给 IPortableDeviceManager 接口上的其他方法,以检索特定于设备的信息,例如友好名称、制造商名称和设备说明。 (这些名称还用于在应用程序调用 IPortableDevice::Open 方法时打开与设备的连接)

if (SUCCEEDED(hr) && (cPnPDeviceIDs > 0))
{
    pPnpDeviceIDs = new (std::nothrow) PWSTR[cPnPDeviceIDs];
    if (pPnpDeviceIDs != NULL)
    {
        DWORD dwIndex = 0;

        hr = pPortableDeviceManager->GetDevices(pPnpDeviceIDs, &cPnPDeviceIDs);
        if (SUCCEEDED(hr))
        {
            // For each device found, display the devices friendly name,
            // manufacturer, and description strings.
            for (dwIndex = 0; dwIndex < cPnPDeviceIDs; dwIndex++)
            {
                printf("[%d] ", dwIndex);
                DisplayFriendlyName(pPortableDeviceManager, pPnpDeviceIDs[dwIndex]);
                printf("    ");
                DisplayManufacturer(pPortableDeviceManager, pPnpDeviceIDs[dwIndex]);
                printf("    ");
                DisplayDescription(pPortableDeviceManager, pPnpDeviceIDs[dwIndex]);
            }
        }
        else
        {
            printf("! Failed to get the device list from the system, hr = 0x%lx\n",hr);
        }

检索设备信息后,需要释放与字符串指针数组指向的字符串关联的内存。 还需要删除此数组。

for (dwIndex = 0; dwIndex < cPnPDeviceIDs; dwIndex++)
{
    CoTaskMemFree(pPnpDeviceIDs[dwIndex]);
    pPnpDeviceIDs[dwIndex] = NULL;
}

// Delete the array of PWSTR pointers
delete [] pPnpDeviceIDs;
pPnpDeviceIDs = NULL;

IPortableDeviceManager 接口

编程指南