Detecting a keypress in python while in the background

后端 未结 2 1604
抹茶落季
抹茶落季 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()
    
    0 讨论(0)
  • 2020-12-06 18:22

    Too get all the properties from your key press event. you can do the following

    import pythoncom, pyHook
    
    def OnKeyboardEvent(event):
        print('MessageName:',event.MessageName)
        print('Message:',event.Message)
        print('Time:',event.Time)
        print('Window:',event.Window)
        print('WindowName:',event.WindowName)
        print('Ascii:', event.Ascii, chr(event.Ascii))
        print('Key:', event.Key)
        print('KeyID:', event.KeyID)
        print('ScanCode:', event.ScanCode)
        print('Extended:', event.Extended)
        print('Injected:', event.Injected)
        print('Alt', event.Alt)
        print('Transition', event.Transition)
        print('---')
    
    # return True to pass the event to other handlers
        return True
    
    # create a hook manager
    hm = pyHook.HookManager()
    # watch for all mouse events
    hm.KeyDown = OnKeyboardEvent
    # set the hook
    hm.HookKeyboard()
    # wait forever
    pythoncom.PumpMessages()
    

    Now know all the details of the key press and do operation on top of this.

    pressing 's' would look like this

    MessageName: key down
    Message: 256
    Time: 449145375
    Window: 2558060
    WindowName: "file name"
    Ascii: 115 s
    Key: S
    KeyID: 83
    ScanCode: 31
    Extended: 0
    Injected: 0
    Alt 0
    Transition 0
    
    0 讨论(0)
提交回复
热议问题