7,659
社区成员




void KeepPowerOn()
{
DWORD cbPowerMsgSize = PM_BROADCAST_QUEUE_SIZE;
MSGQUEUEOPTIONS options;
options.dwSize = sizeof(MSGQUEUEOPTIONS);
options.bReadAccess = TRUE;
options.cbMaxMessage = cbPowerMsgSize;
options.dwMaxMessages = 32;
options.dwFlags = MSGQUEUE_NOPRECOMMIT;
HANDLE hMsgQ = CreateMsgQueue(NULL,&options);
if(NULL == hMsgQ)
{
WriteMessage("[Nosleep]CreateMsgQueue Faild, Error: ",GetLastError());
return;
}
HANDLE hPowerNotify = ::RequestPowerNotifications(hMsgQ,PBT_TRANSITION);
if(NULL == hPowerNotify)
{
WriteMessage("[Nosleep]RequestPowerNotifications Faild, Error: ",GetLastError());
CloseMsgQueue(hMsgQ);
return;
}
union
{
WCHAR buf[PM_BROADCAST_QUEUE_SIZE];
POWER_BROADCAST powerBroadcast;
} u;
DWORD cbRead, dwFlags;
HANDLE hNotify = NULL;
while(TRUE)
{
WaitForSingleObject(hMsgQ,INFINITE);
if(!ReadMsgQueue(hMsgQ,&u,cbPowerMsgSize,&cbRead,0,&dwFlags))
{
WriteMessage("[Nosleep]ReadMsgQueue Faild, Error: ", GetLastError());
break;
}
POWER_BROADCAST ppb = u.powerBroadcast;
switch(ppb.Flags)
{
case 0x00400000:
{
union
{
FILETIME ft;
ULONGLONG ut;
}t;
SYSTEMTIME st;
GetLocalTime(&st);
DWORD dwSeconds=240;
SystemTimeToFileTime(&st, &t.ft);
t.ut+=UInt32x32To64(dwSeconds, 10000000);
FileTimeToSystemTime(&t.ft, &st);
char temp[100];
sprintf(temp,"[Nosleep]sleeping now, will add timer. next run time:%d-%d-%d %d:%d:%d\0",
st.wYear,
st.wMonth,
st.wDay,
st.wHour,
st.wMinute,
st.wSecond);
WriteMessage(temp);
CE_NOTIFICATION_TRIGGER cnt;
cnt.dwSize = sizeof(CE_NOTIFICATION_TRIGGER);
cnt.dwType = CNT_TIME;
cnt.dwEvent = NOTIFICATION_EVENT_NONE;
cnt.lpszApplication = TEXT("notexits.exe");
cnt.lpszArguments = TEXT("");
cnt.stEndTime = st;
cnt.stStartTime = st;
hNotify = CeSetUserNotificationEx(NULL,&cnt,NULL);
if(NULL == hNotify)
{
WriteMessage("[Nosleep]CeSetUserNotificationEx faild ", GetLastError());
}
}
break;
case 0x10000000:
{
WriteMessage("[Nosleep]resuming, clear the timer");
CeClearUserNotification(hNotify);
}
break;
default:
break;
}
}
if(hMsgQ)
::CloseMsgQueue(hMsgQ);
if(hPowerNotify)
::StopPowerNotifications(hPowerNotify);
WriteMessage("Exit now");
}