1.涉及到的消息和API消息:WM_POWERBROADCAST、PBT_APMPOWERSTATUSCHANGEAPI:SYSTEM_POWER_STATUS ps;GetSystemPowerStatus(&ps);2.说明PBT_APMPOWERSTATUSCHANGE这个消息,只有在插入电源和拔掉电源时才会响应,所以如果想要实时检测笔记本电池电量,必须设置一个定时检测的定时器来检测才能实现
3.实现代码1)程序开始处添加定时器:
#define BatteryPowerTimerID 1
//检测笔记本电池电量定时器
SetTimer(BatteryPowerTimerID, 30000, NULL);
void CbatteryDlg::OnTimer(UINT_PTR nIDEvent)
{
// TODO: Add your message handler code here and/or call default
switch (nIDEvent)
{
case BatteryPowerTimerID:
{
CheckBatteryStatus();
}
break;
default:
break;
}
CDialogEx::OnTimer(nIDEvent);
}
void CbatteryDlg::CheckBatteryStatus()
{
SYSTEM_POWER_STATUS ps;
GetSystemPowerStatus(&ps);
int nLife = 0;
//是否使用交流电源
if ( ps.ACLineStatus != AC_LINE_ONLINE )
{
if ( ps.BatteryFlag != BATTERY_FLAG_NO_BATTERY && ps.BatteryFlag != BATTERY_FLAG_UNKNOWN )
{
nLife = ps.BatteryLifePercent;
if ( nLife <= 10 )
{
AfxMessageBox(_T("电量低于10%"));
}
}
}
else
{
AfxMessageBox(_T("有电源供电"));
}
}
2)响应消息
#define WM_POWER_STATUS_MSG (WM_USER+1001)
LRESULT CbatteryDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
// TODO: Add your specialized code here and/or call the base class
switch (message)
{
case WM_POWERBROADCAST:
{
switch(wParam)
{
case PBT_APMPOWERSTATUSCHANGE://电源状态
{
SendMessage(WM_POWER_STATUS_MSG, 0, 0);
}
break;
}
}
break;
}
return CDialogEx::WindowProc(message, wParam, lParam);
}
ON_MESSAGE(WM_POWER_STATUS_MSG, &CbatteryDlg::OnPowerStatus)
LRESULT CbatteryDlg::OnPowerStatus( WPARAM wParam, LPARAM lParam )
{
CheckBatteryStatus();
return 0;
}
Demo下载:
点击下载