tags:

views:

267

answers:

3

I want to prevent the monitor from going to sleep (the windows setting, not the monitor setting). I am using c++. What call do I make?

+12  A: 
class KeepDisplayOn
{
public:
    KeepDisplayOn()
    {
     mPrevExecState = ::SetThreadExecutionState(ES_DISPLAY_REQUIRED | ES_SYSTEM_REQUIRED | ES_CONTINUOUS);
     ::SystemParametersInfo(SPI_GETSCREENSAVETIMEOUT, 0, &mPrevScreenSaver, 0);
     ::SystemParametersInfo(SPI_SETSCREENSAVETIMEOUT, FALSE, NULL, 0);
    }

    ~KeepDisplayOn()
    {
     ::SystemParametersInfo(SPI_SETSCREENSAVETIMEOUT, mPrevScreenSaver, NULL, 0);
     ::SetThreadExecutionState(mPrevExecState);
    }

private:
    UINT    mPrevScreenSaver;
    EXECUTION_STATE  mPrevExecState;
};
sean e
nice use of RAII
Johannes Schaub - litb
But setting the screen saver time out is not necessary once you set the thread execution state to ES_DISPLAY_REQUIRED. What if the user wants to change the screen saver settings while the application's running?
macbirdie
+3  A: 

SetThreadExecutionState(ES_DISPLAY_REQUIRED|ES_CONTINUOUS);

MSN
Would this work?
Nathan Lawrence
As opposed to not working? That's what MSDN recommends.
MSN
+5  A: 

A simpler way that doesn't modify global system state like the first response does:

In your window procedure, add a handler for WM_SYSCOMMAND. When wParam is SC_MONITORPOWER, return 0 instead of deferring to DefWindowProc. (When wParam is any other value, make sure you either handle the message or pass it to DefWindowProc. Otherwise the user will have difficulty adjusting your window at runtime.)

ChrisV
This only works for the foreground window
Anders