How to detect key press when the console window has lost focus

删除回忆录丶 提交于 2019-12-04 12:01:11

I can see 3 possible ways of doing this. The first, would be to bring your window to the top after the mouse click, however I assume this is not what you want to happen.

A second way, which should work fine if all you want is the ESC key, would be to use a hotkey. This could be done using a method similar to this:

import win32con, ctypes, ctypes.wintypes

def esc_pressed():
    print("Escape was pressed.")

ctypes.windll.user32.RegisterHotKey(None, 1, 0, win32con.VK_ESCAPE)

try:
    msg = ctypes.wintypes.MSG()
    while ctypes.windll.user32.GetMessageA(ctypes.byref(msg), None, 0, 0) != 0:
        if msg.message == win32con.WM_HOTKEY:
            esc_pressed()
        ctypes.windll.user32.TranslateMessage(ctypes.byref(msg))
        ctypes.windll.user32.DispatchMessageA(ctypes.byref(msg))
finally:
    ctypes.windll.user32.UnregisterHotKey(None, 1)

For more information on registering a hotkey with Python you can look here.

The third way, which you would have to use if you wanted to catch every key press, would be to set a low level keyboard hook.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!