列舉裝置 (WPD)
大部分應用程式完成的第一項工作是連線到計算機的裝置列舉。 IPortableDeviceManager 介面支援這項工作,以及擷取裝置資訊(例如製造商、易記名稱和描述)。
DeviceEnumeration.cpp模組中的 EnumerateAllDevices 函式包含程式代碼,示範擷取連線裝置計數,一旦擷取計數,就會擷取每個連線裝置的裝置特定資訊。
EnumerateAllDevices 函式會完成四個主要工作:
- 建立可攜式設備管理器物件。
- 獲取已連線裝置的數量。
- 擷取裝置資訊(適用於連接的裝置)。
- 釋放擷取裝置資訊時所使用的記憶體。
下列各節將詳細說明這四項工作。
裝置列舉程式中的第一個步驟是建立可攜式設備管理器物件。 這是藉由呼叫 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;
相關主題