Skip to content

Instantly share code, notes, and snippets.

@brianhassel
Last active December 19, 2023 09:16
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • 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 Jul 22, 2020

It is setting method so, call once in constructor then, it is ok.
Thank you for your code.

@ldaman
Copy link

ldaman commented Oct 1, 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...

@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