Skip to content

Instantly share code, notes, and snippets.

@h4ck4life
Forked from brianhassel/PreventSleep.cs
Created November 6, 2019 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h4ck4life/c88639dca2b879eb2955b205cc56dac5 to your computer and use it in GitHub Desktop.
Save h4ck4life/c88639dca2b879eb2955b205cc56dac5 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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment