6

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.

citykid
  • 9,916
  • 10
  • 55
  • 91

2 Answers2

8

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);
Peter Ritchie
  • 35,463
  • 9
  • 80
  • 98
  • it doesn't work with Windows 10 Pro, any idea? – Zinov Jan 05 '21 at 22:42
  • @Zinov See https://learn.microsoft.com/en-gb/windows/win32/api/winbase/nf-winbase-setthreadexecutionstate?redirectedfrom=MSDN Set with `SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED);` and reset to normal with `SetThreadExecutionState(ES_CONTINUOUS);` The enum to add to the above is `ES_SYSTEM_REQUIRED = 0x00000001` – Jay Croghan Jan 27 '23 at 22:58
3

I think that you should be able to prevent the system from entering sleep mode by periodically calling SetThreadExecutionState with the ES_SYSTEM_REQUIRED parameter.

This article might also be useful.

Mårten Wikström
  • 11,074
  • 5
  • 47
  • 87