What line of code could I use in C++ to disable energy saver?

Go To StackoverFlow.com

5

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?

2009-06-16 19:07
by Nathan Lawrence


13

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;
};
2009-06-16 19:10
by sean e
nice use of RAI - Johannes Schaub - litb 2009-06-16 19:20
But setting the screen saver time out is not necessary once you set the thread execution state to ESDISPLAYREQUIRED. What if the user wants to change the screen saver settings while the application's running - macbirdie 2009-06-17 13:32


5

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.)

2009-06-16 21:56
by ChrisV
This only works for the foreground windo - Anders 2009-06-16 22:30


3

SetThreadExecutionState(ES_DISPLAY_REQUIRED|ES_CONTINUOUS);

2009-06-16 19:12
by MSN
Would this work - Nathan Lawrence 2009-11-28 01:11
As opposed to not working? That's what MSDN recommends - MSN 2009-11-30 18:17


1

Wiggle the mouse every minute or so.

mouse_event(MOUSEEVENTF_MOVE,1,0,0,0);
mouse_event(MOUSEEVENTF_MOVE,-1,0,0,0);
Sleep(60000);
2011-12-06 15:48
by EvilTeach
Ads