How can I prevent Windows OS from entering Sleep mode - .Net [duplicate]
Asked Answered
S

2

5

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.

Swum answered 26/2, 2015 at 19:32 Comment(0)
A
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);
Archivolt answered 26/2, 2015 at 19:53 Comment(2)
it doesn't work with Windows 10 Pro, any idea?Medullated
@Medullated See learn.microsoft.com/en-gb/windows/win32/api/winbase/… 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 = 0x00000001Lyford
D
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.

Dropping answered 26/2, 2015 at 19:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.