How can I prevent Windows OS from entering Sleep mode - .Net

citykid picture citykid · Feb 26, 2015 · Viewed 8.9k times · Source

Using C#, how can I prevent Windows OS from entering Sleep mode?

I know, that I can turn Sleep Mode off, that is what I do now. This question is about preventing the OS from Sleeping while a program is in a long running operation. Afterwards, entering Sleep mode shall be re-enabled again.

Answer

Peter Ritchie picture Peter Ritchie · Feb 26, 2015

It's not recommended that an application change the power settings--that's a user preference and should be done how they see fit. An application can inform the system that it needs it not to go to sleep because it's doing something that requires no user interaction.

The criteria by which the system will sleep is detailed here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa373233(v=vs.85).aspx. this details that an application can call the native function SetThreadExecutionState to inform the system of specific needs that would affect how the system should decide to sleep. If you need the display to be visible regardless of lack of user-interaction, the ES_DISPLAY_REQUIRED parameter should be sent to SetThreadExecutionState.

For example:

public enum EXECUTION_STATE : uint
{
    ES_AWAYMODE_REQUIRED = 0x00000040,
    ES_CONTINUOUS = 0x80000000,
    ES_DISPLAY_REQUIRED = 0x00000002,
}

internal class NativeMethods
{
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
}

//...

NativeMethods.SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED);