Detecting a keypress in python while in the background

后端 未结 2 1605
抹茶落季
抹茶落季 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: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
    

提交回复
热议问题