Windows API: Programmatically Prevent Computer From Going To Sleep

See related: Windows API examples

Ever needed to prevent a Windows computer from going to sleep? Just a single line of code will do it, but use it wisely because many users do not like apps that prevent their PC from going to sleep.

#include <windows.h>

// This sets the appropriate flags to prevent the system going into sleep mode; this is useful if making a screen saver that processes data in the background and can't have the computer sleep
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED);

After an application no longer needs the computer to be awake, restore its ability to sleep with this line of code:

#include <windows.h>

// This allows the system to sleep normally
SetThreadExecutionState(ES_CONTINUOUS);

Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site.
OK