Last active
June 24, 2024 18:42
-
-
Save brianhassel/e918c7b9f1a6265ff8f9 to your computer and use it in GitHub Desktop.
Prevent Computer Sleep in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
I got this to work, after spinning a thread and calling the PreventSleep() every minute. Thank you and awesome work!