Search code examples
pythonpython-3.xwindowskey-bindings

Global Keybindings?


Can we make some global keybindings with python?

I mean when I'm in another application or game if I press X the code do something. I searched for that but only found for Ubuntu or Linux... But I want something for Windows and Python3.x.


Solution: https://pynput.readthedocs.io/en/latest/keyboard.html#global-hotkeys

Solution

  • This is what I found, which works well.
    using the module pynput. It will listen to key press globally. I found the answer here stackoverflow.com/questions/11918999/key-listeners-in-python

    from pynput import keyboard
    
    def on_press(key):
        try:
            print('alphanumeric key {0} pressed'.format(key.char))
        except AttributeError:
            print('special key {0} pressed'.format(key))
            
    listener = keyboard.Listener(on_press=on_press)
    listener.start()