Fnord
Fnord

Reputation: 5875

Detect shift-key presses with python ctypes

I want to detect if CTRL|SHIFT|ALT are held down during the execution of a python script to alter its behavior. So for ex if i run a script with SHIFT held down i want a GUI to pop open instead of a command line... etc...

since msvcrt.kbhit couldn't detect SHIFT key presses i did some digging and found this solution which seemed very promising. I added SHIFT to its hotkey list as a test. Unfortunately if you try the code below in a dos shell you'll see that it correctly detects ESC and NUMLOCK key presses, but it won't catch SHIFT presses and i can't figure why that is.

Any insight would be much appreciated.

import ctypes, ctypes.wintypes
import win32con

# Register hotkeys
ctypes.windll.user32.RegisterHotKey(None, 1, 0, win32con.VK_ESCAPE)
ctypes.windll.user32.RegisterHotKey(None, 1, 0, win32con.VK_NUMLOCK)
ctypes.windll.user32.RegisterHotKey(None, 1, 0, win32con.VK_LSHIFT)
ctypes.windll.user32.RegisterHotKey(None, 1, 0, win32con.VK_RSHIFT)

# Loop until one of the hotkeys are pressed
try:
    msg = ctypes.wintypes.MSG()
    while ctypes.windll.user32.GetMessageA(ctypes.byref(msg), None, 0, 0) != 0:
        if msg.message == win32con.WM_HOTKEY:
            print("KEY PRESSED!")

        ctypes.windll.user32.TranslateMessage(ctypes.byref(msg))
        ctypes.windll.user32.DispatchMessageA(ctypes.byref(msg))

# Cleanup
finally:
    ctypes.windll.user32.UnregisterHotKey(None, 1)

Upvotes: 2

Views: 1807

Answers (1)

iljau
iljau

Reputation: 2221

There's a package named PyHook, that takes care of most low-level details related to input events on windows. It may be worth looking at.

Link to keyboard hooks documentation:

Links to installers:

Upvotes: 2

Related Questions