Get Notified about Windows is Going to Sleep/Wakin

2020-07-08 07:33发布

I am working on an App which has Multiple Threads waiting for different inputs from DLLs and Serial Ports.

I want to add a functionality that before machine going to Sleep, I have to unload certain DLL and On waking up have to Re-load the DLL. For this, I need to get notified on Sleep and Wake up.

I found many files about doing in C# but I want to do this in C++.

I tried using this code Project but could not capture any event. I removed everything related to Window Paint and All that as I do not need it's GUI and kept only main message loop (The While loop in the main)

EDIT:-

I am using this as my main loop:-

 // Start the message loop. 

while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{ 
    if (bRet == -1)
    {
        // handle the error and possibly exit
    }
    else
    {
        TranslateMessage(&msg); 
        DispatchMessage(&msg); 
    }
} 

To be frank I have copied this from CodeProject, and Made only one Modification i.e. Checked GetMessage(..) != 0 from a MSDN Article.

Am I missing something?

Or anyother Solution??

I am using VS2010 and programming in C++

Thanks in Advance!

标签: c++ winapi
1条回答
SAY GOODBYE
2楼-- · 2020-07-08 07:56

Try handling the WM_POWERBROADCAST message

Here's sample code that should work. Apparently you do need to create a window otherwise you don't receive the messages. The sample creates a hidden window to achieve this.

static long FAR PASCAL WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    if(message == WM_POWERBROADCAST)
    {
        //Do something
        return TRUE;
    }
    else
        return DefWindowProc(hWnd, message, wParam, lParam);
}

int _tmain(int argc, _TCHAR* argv[])
{
    WNDCLASS wc = {0};


    // Set up and register window class
    wc.lpfnWndProc = WindowProc;
    wc.lpszClassName = _T("SomeNameYouInvented");
    RegisterClass(&wc);
    HWND hWin = CreateWindow(_T("SomeNameYouInvented"), _T(""), 0, 0, 0, 0, 0, NULL, NULL, NULL, 0);

    BOOL bRet;
    MSG msg;
    while( (bRet = GetMessage( &msg, hWin, 0, 0 )) != 0)
    { 
        if (bRet == -1)
        {
            // handle the error and possibly exit
        }
        else
        {
            TranslateMessage(&msg); 
            DispatchMessage(&msg); 
        }
    }
    return 0;
}
查看更多
登录 后发表回答