Skip to content

Instantly share code, notes, and snippets.

@dzmitry-savitski
Created November 11, 2025 13:03
Show Gist options
  • Select an option

  • Save dzmitry-savitski/3f0a7537b8c08ff92d7151f95e0b20e1 to your computer and use it in GitHub Desktop.

Select an option

Save dzmitry-savitski/3f0a7537b8c08ff92d7151f95e0b20e1 to your computer and use it in GitHub Desktop.
const ffi = require("ffi-napi");
// DWORD SetThreadExecutionState(EXECUTION_STATE esFlags);
const kernel32 = ffi.Library("kernel32", {
SetThreadExecutionState: ["uint", ["uint"]],
});
// Flags from Win32 API
const ES_CONTINUOUS = 0x80000000;
const ES_DISPLAY_REQUIRED = 0x00000002; // keep screen on
// Optional: const ES_SYSTEM_REQUIRED = 0x00000001; // keep system awake
function keepAwake() {
const r = kernel32.SetThreadExecutionState(ES_CONTINUOUS | ES_DISPLAY_REQUIRED);
if (r === 0) throw new Error("SetThreadExecutionState failed");
}
function clearAwake() {
// Clears previous request for this thread
kernel32.SetThreadExecutionState(ES_CONTINUOUS);
}
process.on("SIGINT", () => { clearAwake(); process.exit(0); });
process.on("exit", clearAwake);
keepAwake();
console.log("Display will be kept on. Press Ctrl+C to stop.");
setInterval(() => {}, 1 << 30);
import ctypes, atexit
# DWORD SetThreadExecutionState(EXECUTION_STATE esFlags);
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
SetThreadExecutionState = kernel32.SetThreadExecutionState
SetThreadExecutionState.argtypes = [ctypes.c_uint]
SetThreadExecutionState.restype = ctypes.c_uint
ES_CONTINUOUS = 0x80000000
ES_DISPLAY_REQUIRED = 0x00000002
# Optional: ES_SYSTEM_REQUIRED = 0x00000001
def keep_awake():
r = SetThreadExecutionState(ES_CONTINUOUS | ES_DISPLAY_REQUIRED)
if r == 0:
raise ctypes.WinError(ctypes.get_last_error())
def clear_awake():
SetThreadExecutionState(ES_CONTINUOUS)
atexit.register(clear_awake)
keep_awake()
input("Display is kept on. Press Enter to release and exit...")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment