Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 222
citykid Avatar asked Feb 26 '15 19:02

citykid


People also ask

How do I stop Microsoft Windows from going to sleep?

It will be under the "System and Security" header. Click on the link 'Choose when to turn off the display' from the left pane of the window screen. Set both the drop down menus next to "Sleep" to Never.

Does Windows go to sleep when copying files?

Yes. Because copying a file is a system activity and not user activity. You can read everything in more details at Windows 7 sleeping during operations.


2 Answers

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);
like image 192
Peter Ritchie Avatar answered Oct 24 '22 16:10

Peter Ritchie


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.

like image 37
Mårten Wikström Avatar answered Oct 24 '22 17:10

Mårten Wikström