moses-palmer / pynput

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

Suppress=True only suppress first key press #526

Open jabobian opened 1 year ago

jabobian commented 1 year ago

Description A clear and concise description of what the bug is. I am trying to use Right Mouse Button (or X1, X2 etc) plus multiple keyboard presses to do some task automation. Basically, when RButton is pressed, a keyboard listener is started, and when the RButton is released, I check what keys are pressed in a series. for example, RB-AB means RB pressed, A pressed, B pressed, RB released.

But now it only works well with a single key pressed, the 2nd key press (and the 3rd, and so on) will be flush to the editor where cursor is and this makes the text in the editor polluted.

Platform and pynput version Your operating system and version, and the version of pynput.

Ubuntu 22.04 pynput 1.7.6

To Reproduce If possible, please include a short standalone code sample that reproduces the bug. Remember to surround it with code block markers to maintain indentation!

from pynput import mouse, keyboard

class MyException(Exception): pass

def on_press(key):
    global queue, kb_listener
    if key == keyboard.Key.esc:
        queue = None
        kb_listener.stop()
    else:
        try:
            char = key.char
        except:
            char = key.name + '-'
        if queue == None:
            queue = char
        else:
            queue = queue + char

def on_click(x, y, button, pressed):
    global queue, kb_listener
    if button == mouse.Button.middle and x<15:
        raise MyException(button)
    # elif button == mouse.Button.right:
    elif button == mouse.Button.button8 or button == mouse.Button.button9:
        if pressed==True:
            print('right was down')
            queue = None
            kb_listener = keyboard.Listener(on_press=on_press, suppress=True)
            kb_listener.start()
        else:
            if queue != None:
                print('RB-' + queue)
            kb_listener.stop()

queue=None

# Collect events until released
with mouse.Listener(
        on_click=on_click) as listener:
    try:
        listener.join()
    except MyException as e:
        print('{0} was clicked'.format(e.args[0]))
jabobian commented 1 year ago

OK, I found that the suppress is not global, but only within the terminal (when the cursor or focus is still inside the terminal). So how to suppress the global keyboard event?