Last active
April 27, 2016 07:59
-
-
Save silmang/e3b0b7453f21c4f95b3f5703be754d02 to your computer and use it in GitHub Desktop.
[python] receive key events
This file contains hidden or 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
| from collections import namedtuple | |
| KeyboardEvent = namedtuple('KeyboardEvent', ['event_type', 'key_code', 'scan_code', 'alt_pressed', 'time']) | |
| handlers = [] | |
| def listen(): | |
| from ctypes import windll, CFUNCTYPE, POINTER, c_int, c_void_p, byref | |
| import win32con, win32api, win32gui, atexit | |
| event_types = {win32con.WM_KEYDOWN: 'key down', | |
| win32con.WM_KEYUP: 'key up', | |
| 0x104: 'key down', # WM_SYSKEYDOWN, used for Alt key. | |
| 0x105: 'key up', # WM_SYSKEYUP, used for Alt key. | |
| } | |
| def low_level_handler(nCode, wParam, lParam): | |
| """ | |
| Processes a low level Windows keyboard event. | |
| """ | |
| event = KeyboardEvent(event_types[wParam], lParam[0], lParam[1], lParam[2] == 32, lParam[3]) | |
| for handler in handlers: | |
| handler(event) | |
| return windll.user32.CallNextHookEx(hook_id, nCode, wParam, lParam) | |
| # Our low level handler signature. | |
| CMPFUNC = CFUNCTYPE(c_int, c_int, c_int, POINTER(c_void_p)) | |
| # Convert the Python handler into C pointer. | |
| pointer = CMPFUNC(low_level_handler) | |
| # Hook both key up and key down events for common keys (non-system). | |
| hook_id = windll.user32.SetWindowsHookExA(win32con.WH_KEYBOARD_LL, pointer, win32api.GetModuleHandle(None), 0) | |
| # Register to remove the hook when the interpreter exits. Unfortunately a | |
| # try/finally block doesn't seem to work here. | |
| atexit.register(windll.user32.UnhookWindowsHookEx, hook_id) | |
| while True: | |
| msg = win32gui.GetMessage(None, 0, 0) | |
| win32gui.TranslateMessage(byref(msg)) | |
| win32gui.DispatchMessage(byref(msg)) | |
| if __name__ == '__main__': | |
| def print_event(e): | |
| print(e) | |
| handlers.append(print_event) | |
| listen() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment