def hook_keyboard():
def handler(key_code, event_code):
print("{0} {1}".format(hex(key_code), hex(event_code)))
handle = [None]
def low_level_callback(code, rparam, lparam):
try:
key_code = 0xFFFFFFFF & lparam[0] # key code
handler(key_code, rparam & 0xFFFFFFFF)
finally:
return CallNextHookEx(handle[0], code, rparam, lparam)
callback_pointer = CFUNCTYPE(c_int, c_int, wintypes.HINSTANCE, POINTER(c_void_p))(low_level_callback)
handle[0] = SetWindowsHookExA(WH_KEYBOARD_LL, callback_pointer, GetModuleHandleA(None), 0)
atexit.register(UnhookWindowsHookEx, handle[0])
# Message pumper
message = wintypes.MSG()
while True:
msg = GetMessageW(byref(message), 0, 0, 0)
if msg == -1:
UnhookWindowsHookEx(handle[0])
sys.exit(0)
elif msg == 0: # GetMessage return 0 only if WM_QUIT
sys.exit(0)
else:
TranslateMessage(byref(message))
DispatchMessageW(byref(message))
评论列表
文章目录