Skip to content

Instantly share code, notes, and snippets.

@brianhassel
Last active June 24, 2024 18:42
Show Gist options
  • Save brianhassel/e918c7b9f1a6265ff8f9 to your computer and use it in GitHub Desktop.
Save brianhassel/e918c7b9f1a6265ff8f9 to your computer and use it in GitHub Desktop.
Prevent Computer Sleep in C#
internal static class NativeMethods {
public static void PreventSleep() {
SetThreadExecutionState(ExecutionState.EsContinuous | ExecutionState.EsSystemRequired);
}
public static void AllowSleep() {
SetThreadExecutionState(ExecutionState.EsContinuous);
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern ExecutionState SetThreadExecutionState(ExecutionState esFlags);
[FlagsAttribute]
private enum ExecutionState : uint {
EsAwaymodeRequired = 0x00000040,
EsContinuous = 0x80000000,
EsDisplayRequired = 0x00000002,
EsSystemRequired = 0x00000001
}
}
@SnowyPainter
Copy link

SnowyPainter commented Oct 2, 2020

This does not work. Is the call to PreventSleep should be periodic?
I wired it the PreventSleep and AllowSleep to buttons - tried it out but does not work...

In my program, it works if you don't press the 'Power saving button' in Windows. & you don't have to call PreventSleep periodically

@ldaman
Copy link

ldaman commented Oct 2, 2020

I got this to work, after spinning a thread and calling the PreventSleep() every minute. Thank you and awesome work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment