//全局变量以及宏定义
const UINT WM_USER_NOTIFICATION = RegisterWindowMessage(_T("PowerMes"));
1、首先在程序初始化的时候起一个处理power/battery changes 的线程;
CreateThread(NULL, 0, PowerNotificationThread, (LPVOID)hDlg, 0, NULL);
- PowerNotificationThread:为线程函数
- hDlg:为所属进程的句柄
2、处理power/battery changes 线程函数;
// Report power/battery changes to the battery dialog
static DWORD PowerNotificationThread (PVOID lpParam)
{
DEBUGCHK(lpParam);
BYTE pbMsgBuf[sizeof(POWER_BROADCAST) + sizeof(POWER_BROADCAST_POWER_INFO)];
MSGQUEUEOPTIONS msgopts;
HWND hDlg = (HWND)lpParam;
HANDLE rghWaits[2] = { NULL };
HANDLE hReq = NULL;
DWORD dwRet = 1; // 1 is error
// Create our message queue
memset(&msgopts, 0, sizeof(msgopts));
msgopts.dwSize = sizeof(msgopts);
msgopts.dwFlags = 0;
msgopts.dwMaxMessages = 0;
msgopts.cbMaxMessage = sizeof(pbMsgBuf);
msgopts.bReadAccess = TRUE;
rghWaits[0] = CreateMsgQueue(NULL, &msgopts);
if (!rghWaits[0])
{
ERRORMSG(1, (TEXT("Could not create power message queue/r/n")));
goto EXIT;
}
// Request notifications
hReq = RequestPowerNotifications(rghWaits[0], PBT_POWERINFOCHANGE);
if (!hReq)
goto EXIT;
rghWaits[1] = g_hPowerTerminateEvent;
while(TRUE)
{
DWORD dwWaitCode = WaitForMultipleObjects(2, rghWaits, FALSE, INFINITE);
if(dwWaitCode == WAIT_OBJECT_0)
{
DWORD dwSize, dwFlags;
if (ReadMsgQueue(rghWaits[0], pbMsgBuf, sizeof(pbMsgBuf), &dwSize, 0, &dwFlags))
{
//把消息队列以自定义消息的方式发给应用程序。
SendMessage(hDlg, WM_USER_NOTIFICATION, 0, (LPARAM) pbMsgBuf);
}
else
{
DEBUGCHK(FALSE); // We should never get here
}
}
else
{
// got terminate signal
break;
}
}
dwRet = 0; // Success!
EXIT:
// Clean up
if (hReq) StopPowerNotifications(hReq);
if (rghWaits[0]) CloseHandle(rghWaits[0]);
return dwRet;
}
3、接收自定义消息
- evc下 ,在MessageMap 中加入
ON_REGISTERED_MESSAGE(WM_USER_NOTIFICATION, BatteryOnChange)
- Pb 下,在过程函数中 加入
case WM_USER_NOTIFICATION:
BatteryOnChange((PPOWER_BROADCAST) lParam);
4、处理Battery Change 函数
void BatteryOnChange(HWND hDlg, const PPOWER_BROADCAST ppb)
{
// if supported by driver, get lifetime info
if(BatteryDrvrSupportsChangeNotification())
{
//API ,看系统是否支持发BatteryChange Notification;
//如果支持,则在此处加入根据PPOWER_BROADCAST 中Power 变化做出相应动作。
}
}
原文:http://blog.sina.com.cn/s/blog_543ef0f4010006yi.html~type=v5_one&label=rela_prevarticle