Search code examples
pythonpython-3.xkeyboardkeyboard-shortcuts

I can't figure out how to make a function to catch keyboard shortcuts correctly


When I hold down a modifier key (shift, ctrl, alt), I need to press the second key very quickly, otherwise I get, for example, shift + shift. and the second problem: if I just click on the same shift, I also get shift + shift

def hotkey(widget):
    key = keyboard.read_key()
    modificator = ["shift", "ctrl", "alt"]
    if keyboard.is_pressed(modificator[0]):
        modkey = keyboard.read_key()
        key = modificator[0] + " + " + modkey
    elif keyboard.is_pressed(modificator[1]):
        modkey = keyboard.read_key()
        key = modificator[1] + " + " + modkey
    elif keyboard.is_pressed(modificator[2]):
        modkey = keyboard.read_key()
        key = modificator[2] + " + " + modkey
    widget.value = key.title()
    widget.update()
    print(key)

I need it to wait as long as necessary for the second key when holding down the modifier key, and so that when you click on the modifier, it returns only the key. Sorry for my english if i wrote something wrongy.


Solution

  • Here is a (fairly complex) code that should do what you want. It should catch all Ctrl/Alt/Shift+Key combinations.

    # Import the keyboard module
    import keyboard
    
    # Define a list of modifier keys
    modifiers = ["ctrl", "alt", "shift"]
    
    # Initialize the modifier variable as None
    modifier = None
    
    # Define a function to handle key press events
    def on_press(event):
        # Get the name of the pressed key
        key = event.name
    
        # Check if the key is a modifier key
        if key in modifiers:
            # Set the global variable to store the modifier key
            global modifier
            modifier = key
        else:
            # Check if there is a modifier key stored
            if modifier:
                # Print the shortcut combination
                print(modifier + "+" + key)
                # Reset the modifier variable
                modifier = None
    
    # Define a function to handle key release events
    def on_release(event):
        # Get the name of the released key
        key = event.name
    
        # Check if the key is a modifier key
        if key in modifiers:
            # Check if there is no other modifier key pressed
            if not any(keyboard.is_pressed(m) for m in modifiers):
                # Print the modifier key alone
                print(key)
                # Reset the modifier variable
                global modifier
                modifier = None
    
    # Hook the functions to the keyboard events
    keyboard.on_press(on_press)
    keyboard.on_release(on_release)
    
    # Wait for the user to press Esc to exit
    keyboard.wait("esc")