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.
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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With