当系统的电源状态该变时,可以通过RequestPowerNotifications要求电源管理器向自己发送一个通知
HANDLE RequestPowerNotifications(
HANDLE hMsgQ,
DWORD Flags
);
示例:
#include
#include
#include
#define MAX_NOTIFY_NAMELEN 128
#define PM_BROADCAST_QUEUE_SIZE ((sizeof(POWER_BROADCAST) + (MAX_NOTIFY_NAMELEN * sizeof(WCHAR) ) ) )
#define SIZEOFARRAY(a) (sizeof(a) / sizeof(a[0]))
void IlockDThreadProc(void)
{
MSGQUEUEOPTIONS mqo;
HANDLE hPowerMsgQ;
HANDLE hPowerNotifications;
DWORD cbRead;
DWORD dwFlags;
DWORD cbPowerMsgSize = PM_BROADCAST_QUEUE_SIZE;
DWORD dwPwrFlags;
TCHAR szPowerState[32];
POWER_BROADCAST ppb;
union {
WCHAR buf[PM_BROADCAST_QUEUE_SIZE];
POWER_BROADCAST powerBroadcast;
} u;
printf("IlockDThreadProc/n");
mqo.dwSize = sizeof(MSGQUEUEOPTIONS);
mqo.dwFlags = MSGQUEUE_NOPRECOMMIT;
mqo.dwMaxMessages = 32;
mqo.cbMaxMessage = cbPowerMsgSize;
mqo.bReadAccess = TRUE;
hPowerMsgQ = CreateMsgQueue(NULL, &mqo);
if (NULL == hPowerMsgQ) {
printf("/r/n/r/nCreateMsgQueue failed: %x/n", GetLastError());
goto Error;
}
hPowerNotifications = RequestPowerNotifications(hPowerMsgQ, PBT_ALL);
if (NULL == hPowerNotifications) {
printf("RequestPowerNotifications failed: %x/n", GetLastError());
goto Error;
}
while(1) {
WaitForSingleObject(hPowerMsgQ,INFINITE);
if (!ReadMsgQueue(hPowerMsgQ, &u, cbPowerMsgSize, &cbRead, 0, &dwFlags)) {
printf("ReadMsgQueue failed: %x/n", GetLastError());
ASSERT(FALSE);
}
ppb = u.powerBroadcast;
switch(ppb.Message) {
case PBT_TRANSITION:
printf("##############################ppb.Message PBT_TRANSITION/n");
GetSystemPowerState(szPowerState,SIZEOFARRAY(szPowerState),&dwPwrFlags);
if(!wcscmp(TEXT("backlightoff"),szPowerState)) {
printf("BacklightOff/n");
break;
}
if(!wcscmp(TEXT("unattended"),szPowerState)) {
printf("unattended/n");
break;
}
break;
case PBT_RESUME:
printf("##############################ppb.Message PBT_RESUME/n");
break;
case PBT_POWERSTATUSCHANGE:
printf("************************ppb.Message PBT_POWERSTATUSCHANGE/n");
break;
case PBT_POWERINFOCHANGE:
printf("##############################ppb.Message PBT_POWERINFOCHANGE/n");
break;
default:
printf("##############################ppb.Message default/n");
break;
}
}
Error:
if (hPowerMsgQ)
CloseMsgQueue(hPowerMsgQ);
if (hPowerNotifications)
StopPowerNotifications(hPowerNotifications);
}
int _tmain(void)
{
CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)IlockDThreadProc,0,0,NULL);
while(1) {
Sleep(1000);
}
}