简体   繁体   中英

Pynput trigger physical button press. Hotkey pressing not working

The code is working fine the hotkey for the function is recognized and the buttons are being pressed.

An OBS function is triggered by the HotKey in hotkey_e().

When I press it physicaly it works. But when I run this script the obs function doesn't get triggered.

The only difference I've found through the print is that if you press the combination it prints <69> (for e) but if the script is pressing this combination it gives me a string "w"

Print output

from pynput.keyboard import Key, Controller, Listener, HotKey

kc = Controller()

def hotkey_e():
    kc.press(Key.alt_l)
    kc.press(Key.ctrl_l)
    kc.press(Key.shift)
    kc.press("w")
    kc.release(Key.alt_l)
    kc.release(Key.ctrl_l)
    kc.release(Key.shift)
    kc.release("w")

HOTKEYS = [HotKey(HotKey.parse("<shift>+<ctrl>+<alt>+" + "e"), hotkey_e)]

def on_press(key):
    if key == Key.esc:
        listener.stop()

    print(str(key))
    
    for hotkey in HOTKEYS:
        hotkey.press(listener.canonical(key))


def on_release(key):
    for hotkey in HOTKEYS:
        hotkey.release(listener.canonical(key))


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

I also tried

with kc.pressed(Key.alt):
        with kc.pressed(Key.ctrl):
            with kc.pressed(Key.shift):
                kc.press("w")
                kc.release("w")

Edit: I found out that if I the OBS windows is the active window the HotKey is working. But it should run in background

My solution was to set some sleep between the key presses

def hotkey_e():
    kc.press(Key.alt_l)
    time.sleep(0.05)
    kc.press(Key.ctrl_l)
    time.sleep(0.05)
    kc.press(Key.shift)
    time.sleep(0.05)
    kc.press("w")
    time.sleep(0.05)
    kc.release(Key.alt_l)
    time.sleep(0.05)
    kc.release(Key.ctrl_l)
    time.sleep(0.05)
    kc.release(Key.shift)
    time.sleep(0.05)
    kc.release("w")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM