In a Visual Studio C++ MFC application you will need to add an ON_MESSAGE()
to your message map looking for the WM_POWERBROADCAST
message as in this example:
BEGIN_MESSAGE_MAP(CFrameworkWndApp, CWinApp)
//{{AFX_MSG_MAP(CFrameworkWndApp)
ON_WM_CHAR()
ON_WM_TIMER()
//}}AFX_MSG_MAP
ON_MESSAGE(WM_POWERBROADCAST, OnPowerMsgRcvd)
END_MESSAGE_MAP()
Then you will need to add the message handler function along with the class definition change to declare the member function for the message handler so that you can check the wParam
variable for the message type as in this skeleton. Remember to return an LRESULT
value indicating if you handled the message or not.
// Handle the WM_POWERBROADCAST message to process a message concerning power management
// such as going to Sleep or Waking Up.
LRESULT CFrameworkWndApp::OnPowerMsgRcvd(WPARAM wParam, LPARAM lParam)
{
LRESULT lrProcessed = 0; // indicate if message processed or not
switch (wParam) {
case PBT_APMPOWERSTATUSCHANGE:
TRACE0("PBT_APMPOWERSTATUSCHANGE received\n");
break;
case PBT_APMRESUMEAUTOMATIC:
TRACE0("PBT_APMRESUMEAUTOMATIC received\n");
break;
case PBT_APMRESUMESUSPEND:
TRACE0("PBT_APMRESUMESUSPEND received\n");
break;
case PBT_APMSUSPEND:
TRACE0("PBT_APMSUSPEND received\n");
break;
}
// indicate if framework needs to handle message or we did ourselves.
return lrProcessed;
}
See Microsoft documentation - Power Management as well as the particular subsection of that documentation Microsoft documentation - WM_POWERBROADCAST message for details on handling the message.
See also the SetThreadExecutionState() function which affects how Windows determines whether an application is active or not and whether sleep mode should be entered or not.
See also the following Stack Overflow postings: