共用方式為


使用裝置電源 API

使用裝置電來源程式設計項目來管理當系統處於睡眠狀態時裝置執行的方式。

開啟和關閉裝置清單

在 CPU 時間方面,開啟和關閉裝置清單是昂貴的程式。 只有在應用程式需要多次查詢裝置清單時,才需要執行這項操作的 DevicePowerOpenDevicePowerClose 函式。

如果呼叫 DevicePowerOpen ,則必須在裝置清單查詢完成時呼叫 DevicePowerClose如果 DevicePowerOpen 已明確開啟裝置清單,DevicePowerEnumDevicesDevicePowerSetDeviceState 將不會關閉 裝置清單。

列舉裝置

DevicePowerEnumDevices函式會偵測裝置清單是否已開啟,如果未開啟,則會開啟它。 DevicePowerEnumDevices 會 根據指定的搜尋準則列舉裝置。 如果函式已開啟裝置清單,則會在函式傳回之前關閉。

啟用和停用裝置,使其無法喚醒系統

DevicePowerSetDeviceState函式與DevicePowerEnumDevices類似,會偵測裝置清單是否已開啟,如果未開啟,則會開啟它。 DevicePowerSetDeviceState 接著會設定指定裝置的指定準則。 如果函式已開啟裝置清單,則會在函式傳回之前關閉。

範例程式碼

下列範例示範如何使用裝置 Power API。

#define _WIN32_WINNT 0x0600
#include <Windows.h>
#include <PowrProf.h>
#include <stdio.h>
#include <tchar.h>

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

int __cdecl main()
{
 // Define and initialize our return variables.
 LPWSTR  pRetBuf = NULL;
 ULONG bufSize = MAX_PATH * sizeof(WCHAR);
 ULONG uIndex = 0;
 BOOLEAN bRet = FALSE;

 // Open the device list, querying all devices
 if (!DevicePowerOpen(0)) 
  {
   printf("ERROR: The device database failed to initialize.\n");
   return FALSE;
  }

 // Enumerate the device list, searching for devices that support 
 // waking from either the S1 or S2 sleep state and are currently 
 // present in the system, and not devices that have drivers 
 // installed but are not currently attached to the system, such as 
 // in a laptop docking station.

 pRetBuf = (LPWSTR)LocalAlloc(LPTR, bufSize);

 while (NULL != pRetBuf && 
        0 != (bRet = DevicePowerEnumDevices(uIndex,
           DEVICEPOWER_FILTER_DEVICES_PRESENT,
           PDCAP_WAKE_FROM_S1_SUPPORTED|PDCAP_WAKE_FROM_S2_SUPPORTED,
           (PBYTE)pRetBuf,
           &bufSize)))
  {
   printf("Device name: %S\n", pRetBuf);

   // For the devices we found that have support for waking from 
   // S1 and S2 sleep states, disable them from waking the system.
   bRet = (0 != DevicePowerSetDeviceState((LPCWSTR)pRetBuf, 
                                  DEVICEPOWER_CLEAR_WAKEENABLED, 
                                  NULL));

   if (0 != bRet) 
    {
     printf("Warning: Failed to set device state.\n");
    }
   uIndex++;
  }

 // Close the device list.
 DevicePowerClose();
 if (pRetBuf!= NULL) LocalFree(pRetBuf);
 pRetBuf = NULL;

 return TRUE;
}

在此範例中,裝置清單會開啟一次,並關閉一次。 如果未呼叫 DevicePowerOpenDevicePowerClose 函式,則每個 呼叫 DevicePowerEnumDevicesDevicePowerSetDeviceState都會開啟並關閉裝置清單。 藉由使用 DevicePowerOpenDevicePowerClose ,我們儲存了開啟裝置清單兩次不必要的時間。