Skip to content
Aditya Bhalsod
← Open Source
Open SourceIntermediate

Keeping Windows Awake From Python With ctypes and SendInput

How Auto Warm-Up talks to Win32 from plain Python, what SendInput and SetThreadExecutionState do, and a thread-stop bug that is easy to write in a loop like this.

  • #python
  • #windows
  • #ctypes
  • #win32-api
Contents
  1. Declaring SendInput by hand
  2. A jiggle that nets out to zero
  3. Stopping a thread that is asleep
  4. Building the executable
  5. Where this fits

Auto Warm-Up is a Windows tray utility in a single Python file that stops a session from going idle. People use tools like this for long-running jobs, presentations or a screen that only needs to be watched. The code is small, which makes it a good place to see how little it takes to call Win32 from Python with nothing but ctypes.

This post covers the two API calls it relies on, a threading mistake that is easy to make in a loop like this one, and the build setup around it.

Declaring SendInput by hand

The tray icon comes from pystray and Pillow, both pinned in requirements.txt. Everything that talks to Windows uses the standard library: ctypes, ctypes.wintypes and winreg.

SendInput takes INPUT structures, so auto_warm_up.py redeclares them:

Python
class MOUSEINPUT(ctypes.Structure):
    _fields_ = [
        ("dx", ctypes.wintypes.LONG),
        ("dy", ctypes.wintypes.LONG),
        ("mouseData", ctypes.wintypes.DWORD),
        ("dwFlags", ctypes.wintypes.DWORD),
        ("time", ctypes.wintypes.DWORD),
        ("dwExtraInfo", ctypes.POINTER(ctypes.c_ulong)),
    ]

class INPUT(ctypes.Structure):
    class _INPUT(ctypes.Union):
        _fields_ = [("mi", MOUSEINPUT)]  # only the mouse variant

    _fields_ = [("type", ctypes.wintypes.DWORD), ("ii", _INPUT)]

In C, INPUT is a tagged union: the type field says which member is valid. I declared a union with only the mouse member, because mouse movement is the only event the app sends. Sending it is a few lines:

Python
def move_mouse(dx, dy):
    mouse_input = MOUSEINPUT(
        dx=dx, dy=dy, mouseData=0,
        dwFlags=MOUSEEVENTF_MOVE, time=0,
        dwExtraInfo=ctypes.pointer(ctypes.c_ulong(0)),
    )
    input_event = INPUT(type=INPUT_MOUSE)
    input_event.ii.mi = mouse_input
    ctypes.windll.user32.SendInput(1, ctypes.byref(input_event), ctypes.sizeof(INPUT))

Only MOUSEEVENTF_MOVE is set, and the docstring calls it a relative movement, so dx and dy are deltas from the current position. The return value of SendInput is discarded, so a rejected call would fail silently.

A jiggle that nets out to zero

The loop that drives it is short:

Python
def prevent_idle(interval_seconds=30, stop_event=None):
    direction = 1
    while not (stop_event and stop_event.is_set()):
        move_mouse(direction, 0)
        direction *= -1
        # ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED
        ctypes.windll.kernel32.SetThreadExecutionState(0x80000000 | 0x00000001 | 0x00000002)
        time.sleep(interval_seconds)

Each pass sends a one-pixel move, alternately right and left, so the pointer is back where it started after every two passes. Then it calls SetThreadExecutionState with three flags. The first part is synthetic input that Windows counts as activity. The second is an explicit request that the system and display stay on, which the README compares to what a video player does. The code uses both. They overlap, and the repo does not say whether either would be enough alone.

The worker runs on a daemon thread while the tray icon's event loop blocks the main thread in icon.run(). The menu has Start, Stop, Start on Boot and Quit. Start on Boot is opt-in and writes a value under the per-user Run registry key, so it needs no admin rights.

Stopping a thread that is asleep

Stop is stop_event.set(). The loop checks the event once per pass, after time.sleep(interval_seconds), so a thread that is mid-sleep can take up to 30 seconds to notice.

That interacts with Start, which only creates a new thread when the old one is gone:

Python
def start_jiggler(icon, item):
    if jiggler_thread[0] is None or not jiggler_thread[0].is_alive():
        stop_event.clear()
        jiggler_thread[0] = threading.Thread(target=prevent_idle, args=(30, stop_event), daemon=True)
        jiggler_thread[0].start()
        icon.icon = create_icon_image("green")

The fix I would make is to replace time.sleep(interval_seconds) with stop_event.wait(interval_seconds). It returns as soon as the event is set, so the thread exits almost at once. Console mode calls prevent_idle with no event, so that path needs a plain sleep as a fallback. I would also add a final SetThreadExecutionState call with only ES_CONTINUOUS on exit, because nothing in the file clears the request explicitly.

Building the executable

The build setup has changed shape. The README's pipeline diagram and the repository description still describe the older Docker and Wine build, so the workflow file is the source of truth.

release.yml runs four jobs on pushes to main, beta or alpha: prepare, build, sign and release. The build job runs on windows-latest and compiles with Nuitka (--standalone --onefile, console disabled, no UPX). The comments give the reason: PyInstaller's one-file bootloader is the same in every build, and antivirus engines fingerprint it. The repo has no measurements, so that is the reasoning, not a result.

The sign job picks a method from the secrets it finds. SignPath comes first, then a PFX certificate through sign_exe.sh and osslsigncode. With neither, the release ships unsigned on purpose, because the comments say a self-signed signature makes scanners more suspicious. sign_exe.sh keeps a self-signed fallback behind ALLOW_SELF_SIGN=1.

PathBuilderRuns onSigning
build.batNuitka, or PyInstaller with --pyinstallerLocal WindowsNone in the script
GitHub ActionsNuitkawindows-latestSignPath or PFX if secrets exist
build_linux.shPyInstaller under WineDocker on LinuxNone in the Dockerfile

The Dockerfile route stays for building from Linux. It uses tobix/pywine:3.12, and its comment says Nuitka under Wine is not reliably supported.

Where this fits

For a personal utility the size is about right: one source file, two pinned runtime dependencies and no installer. It stops being enough in a few places. Nothing reads the last-input time, so it acts every interval whether or not anyone is at the keyboard. The interval defaults to 30, but all three callers pass 30 themselves, so changing the default alone changes nothing. It is Windows only, and the repo has no tests.

If I rewrote it, I would check how long the machine has been idle before sending anything, switch to Event.wait, and release the execution-state request on exit. The ctypes part I would keep as it is.

Found this useful? Share it with your team.

Keep reading

More from Open Source and beyond