Skip to content

Instantly share code, notes, and snippets.

@kms70847
Last active January 13, 2016 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kms70847/a5dfba1b2597cf8e7404 to your computer and use it in GitHub Desktop.
Save kms70847/a5dfba1b2597cf8e7404 to your computer and use it in GitHub Desktop.
import win32api, win32con
import time
import threading
import sys
def is_pressed(key):
x = win32api.GetKeyState(key)
return (x & (1 << 8)) != 0
#executes `callback` whenever the key state changes from off to on.
#terminates when the user presses the Q button.
def key_detection_thread(key, callback):
keys = {key: "pressed", ord("Q"): "quit"}
prev_states = {key: False for key in keys.iterkeys()}
while True:
for key, msg in keys.iteritems():
prev_state = prev_states[key]
cur_state = is_pressed(key)
if cur_state and not prev_state:
if msg == "quit": return
if msg == "pressed": callback()
prev_states[key] = cur_state
time.sleep(0.01)
#spawn `key_detection_thread` asynchronously so the while loop doesn't block the rest of your program forever.
def listen(key, callback):
t = threading.Thread(target=key_detection_thread, args=(key, callback))
t.daemon = True
t.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment