-
-
Save kms70847/a5dfba1b2597cf8e7404 to your computer and use it in GitHub Desktop.
This file contains 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
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