moses-palmer / pynput

Sends virtual input commands
GNU Lesser General Public License v3.0
1.77k stars 245 forks source link

Hotkey modifier not needed (perhaps system views as pressed) after ALT+TAB #500

Closed jb261 closed 1 year ago

jb261 commented 1 year ago

Hotkey modifier not needed (perhaps system views as pressed) after ALT+TAB

Windows 10, Python 3.9.12, pynput 1.7.6

from pynput import keyboard

def function_1():
    print('Function 1 activated')

with keyboard.GlobalHotKeys({
        '<alt>+<ctrl>+b': function_1}
        ) as h:
    h.join()

Expected behavior is that the function (a print statement) executes every time CTRL+ALT+B is pressed, but not any other key combination. I'm finding CTRL+ALT+SHIFT+B also triggers the function. I guess this makes sense if the listener code isn't excluding keys that are not in the set it is listening for.

After pressing ALT+Tab to switch windows, CTRL+B will also trigger the function. Almost as if the code sees ALT key as being held down? But I find CTRL+B does not trigger function after ALT+[some other key], but does reliably trigger function after ALT+TAB.

jb261 commented 1 year ago

I think this is same/related problem.

Windows 10, Python 3.9.12, pynput 1.7.6

from pynput import keyboard
import clipboard 
import time
import pygetwindow as gw

def copy_clipboard():
    print(gw.getActiveWindowTitle())
    time.sleep(0.50)  
    return clipboard.paste()

def function_1():
    print('Function 1 activated')
    clipboardContents = copy_clipboard()
    # print(clipboardContents)

with keyboard.GlobalHotKeys({
        '<ctrl>+<alt>+b': function_1}
        ) as h:
    h.join()

Expected behavior is function triggers only on CTRL+ALT+B, which appears to be the case initially. But after CTRL+ALT+B has been pressed, CTRL+ALT will trigger the function. Pressing CTRL+ALT+B again turns off the ability of CTRL+ALT to trigger the function. Pressing CTRL+ALT+B again turns on the ability of CTRL+ALT to trigger the function.

jb261 commented 1 year ago

Issue resolved. I guess with the way I'm using keyboard.GlobalHotKeys(), at least 2 hotkeys must be specified.

If I substitute the following into the code above, the hotkeys work as expected.

with keyboard.GlobalHotKeys({
        '<alt>+<shift>+u': function_1,
        '<ctrl>+<alt>+b': function_2}
        ) as h:
    h.join()