Search code examples
hookpower-managementwindows-messages

How to detect Windows suspend message?


Does somebody know how to detect a Windows suspend message by C/C++ code?

Or, does SetWindowsHookEx() function do this?

Does somebody have these code for me? I want to detect this message.


Solution

  • If you are talking about sleep and hibernate – the answer is yes, you can. You just need to listen to WM_POWERBROADCAST message.

    Suppose you have an MFC application and a window class which is a subclass of CWnd. Then you can do:

    BEGIN_MESSAGE_MAP(CMyWindow, CWnd)
        //{{AFX_MSG_MAP(CMyWindow)
        ON_MESSAGE(WM_POWERBROADCAST, OnMsgPowerBroadcast)
        //}}AFX_MSG_MAP
    END_MESSAGE_MAP()
    
    ...
    
    LRESULT CMyWindow::OnMsgPowerBroadcast(WPARAM wParam, LPARAM lParam)
    {
        if (wParam == PBT_APMSUSPEND) {
            // The system is suspending.
        }
        return TRUE; 
    }