Device Power API の使用

Device Power プログラミング要素を使用して、システムがスリープ状態にある間のデバイスの実行方法を管理します。

デバイスリストを開いて閉じる

デバイスの一覧を開いたり閉じたりすると、CPU 時間の観点からコストのかかるプロセスになります。 これを行う DevicePowerOpen 関数と DevicePowerClose 関数は、アプリケーションがデバイス一覧に複数回クエリを実行する必要がある場合にのみ必要です。

DevicePowerOpen が呼び出される場合は、デバイス一覧クエリが完了したときに DevicePowerClose を呼び出す必要があります。 DevicePowerEnumDevices と DevicePowerSetDeviceState は、 DevicePowerOpen によって明示的に開かれている場合、デバイス リストを閉じません。

デバイスの列挙

DevicePowerEnumDevices 関数は、デバイス リストが開いているかどうかを検出し、開かない場合は開きます。 DevicePowerEnumDevices は、 指定した検索条件に基づいてデバイスを列挙します。 デバイスリストが関数によって開かれた場合、関数が戻る前に閉じられます。

デバイスによるシステムのスリープ解除の有効化と無効化

DevicePowerSetDeviceState 関数は、DevicePowerEnumDevices と同様に、デバイス リストが開いているかどうかを検出し、開かない場合は開きます。 次に、DevicePowerSetDeviceState は、指定したデバイスの指定した条件を設定します。 デバイスリストが関数によって開かれた場合、関数が戻る前に閉じられます。

コード例

次の例では、Device 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;
}

この例では、デバイス リストは 1 回開き、1 回閉じられます。 DevicePowerOpen 関数と DevicePowerClose 関数が呼び出されなかった場合、DevicePowerEnumDevices と DevicePowerSetDeviceState の各呼び出しによって、デバイスリストが開かれて閉じられました。 DevicePowerOpen と DevicePowerClose を使用して、デバイス リストを 2 回不要に開くのを保存しました。