Detecting a keypress in python while in the background

后端 未结 2 1610
抹茶落季
抹茶落季 2020-12-06 17:51

I am trying to find a way to detect a keypress and then run a method depending on what key it is.

I can already do this with Tkinter. But what I can\'t do is dete

2条回答
  •  臣服心动
    2020-12-06 18:05

    pyHook seems like it would work well for this (mentioned by furas)

    from pyHook import HookManager
    from win32gui import PumpMessages, PostQuitMessage
    
    class Keystroke_Watcher(object):
        def __init__(self):
            self.hm = HookManager()
            self.hm.KeyDown = self.on_keyboard_event
            self.hm.HookKeyboard()
    
    
        def on_keyboard_event(self, event):
            try:
                if event.KeyID  == keycode_youre_looking_for:
                    self.your_method()
            finally:
                return True
    
        def your_method(self):
            pass
    
        def shutdown(self):
            PostQuitMessage(0)
            self.hm.UnhookKeyboard()
    
    
    watcher = Keystroke_Watcher()
    PumpMessages()
    

提交回复
热议问题