C#C
C#3y ago
Ben

Best approach to SetThreadExecutionState

Hey!
I got an app that takes a periodic screenshot of open windows.
Some customers reported that after being idle for a while the screenshots seems to freeze.
Did some googling and it seems like once the OS/Monitor goes into idle/sleep state it stops rendering new frames (somewhat similar to what happens when you minimize a video and check its preview via winkey+tab).

This is the solution I found -
https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setthreadexecutionstate?redirectedfrom=MSDN

Using the above my goal is to keep the OS rendering new frames so the screenshots are up to date but I don't actually need the monitor itself to be visible.

I want to make sure I plan to use it correctly -
On the app main thread I'll run -
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED);


If I understood correctly, using ES_CONTINUOUS means I don't have to run this command periodically, as long as the thread is alive the state will remain.
ES_AWAYMODE_REQUIRED is basically exactly what I'm looking for to keep rendering new frames but not to force active monitor.
ES_SYSTEM_REQUIRED is this necessary?

And on application shutdown I'll run -
SetThreadExecutionState(ES_CONTINUOUS);

To revert changed settings.

Sounds correct?
Was this page helpful?