Search code examples
pythonkeyboardpynput

How can i detect key combinations in Windows python3+?


I am trying to program something that detects when a key combination is pressed and calls a certain function. So i need the program to detect something like ctrl+v when pressed and do something, but it seems like the program does not recognize ctrl+v together, but it does when i am only testing for 1 key:

COMBINATION = [
    {keyboard.Key.ctrl, keyboard.KeyCode(char='v')}
]

In this code, if i remove 1 of the 2 the program seems to detect the key, but if they're togeter it does not. This is what i'm using to detect the keys:

def on_press(key):
    if any([key in COMBO for COMBO in COMBINATION]):
        current.add(key)
        if any(all(k in current for k in comb) for comb in COMBINATION):
            execute()

the execute() function never gets executed if both parameters are placed in COMBINATION but if there's only one it seems like it does work. I am using pynput for keys pressed and a listener that listens to all key pressed:

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

Thanks!


Solution

  • so there's a super simple library called keyboard

    Install it with pip install keyboard

    import keyboard
    
    if keyboard.is_pressed('ctrl+v'):
       # Call your function
    

    I hope that I helped you.