Created
March 12, 2026 20:48
-
-
Save MatthewSteeples/e6b2c8dfe9bee5ac205f8833f995e16c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| using System.Runtime.InteropServices; | |
| namespace Ledgerscope.Utilities.NativeMethods | |
| { | |
| public partial class SleepPreventer : IDisposable | |
| { | |
| public SleepPreventer() | |
| { | |
| SetThreadExecutionStateHelper.PreventSleep(); | |
| } | |
| public void Dispose() | |
| { | |
| SetThreadExecutionStateHelper.AllowSleep(); | |
| GC.SuppressFinalize(this); | |
| } | |
| private static partial class SetThreadExecutionStateHelper | |
| { | |
| [FlagsAttribute] | |
| public enum EXECUTION_STATE : uint | |
| { | |
| ES_AWAYMODE_REQUIRED = 0x00000040, | |
| ES_CONTINUOUS = 0x80000000, | |
| ES_DISPLAY_REQUIRED = 0x00000002, | |
| ES_SYSTEM_REQUIRED = 0x00000001 | |
| // Legacy flag, should not be used. | |
| // ES_USER_PRESENT = 0x00000004 | |
| } | |
| [LibraryImport("kernel32.dll")] | |
| private static partial uint SetThreadExecutionState(EXECUTION_STATE esFlags); | |
| public static void PreventSleep() | |
| { | |
| if (Environment.OSVersion.Platform == PlatformID.Win32NT) | |
| _ = SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_SYSTEM_REQUIRED); | |
| } | |
| public static void AllowSleep() | |
| { | |
| if (Environment.OSVersion.Platform == PlatformID.Win32NT) | |
| _ = SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment