How to suppress/unsuppress mouse events on demand in Python?

53 Views Asked by At

This code will suppress the mouse events

pynput.mouse.Listener(on_move=onMove, on_click=onClick, on_scroll=onScroll, suppress=True)

but I want something like

def on_move(x,y):   
    if(something):     
        resend(x,y)   
    else:     
        //do something 

I tried to resend using

pynput.mouse.Controller().move(x,y) and pyautogui.moveRel(x,y) but it didn't work.

1

There are 1 best solutions below

0
5rod On

Ok, I don't understand why you would want to do this, but here's what I came up with:

from pynput.mouse import Listener

def on_suppress_move(x, y):
    #do stuff
    if not condition:
        return False

def on_move(x, y):
    #do stuff
    if condition:
        return False

while True:
    if(condition):
        with Listener(on_move=on_suppress_move, suppress=True) as listener:
            listener.join()
    
    else:
        with Listener(on_move=on_move) as listener:
            listener.join()

This should work. We run through a while loop, constantly checking if the condition is True/False depending on the function. We return False from the function (and therefore stop the listener) when the condition is not met. After the else statement is finished, the loop starts over again (and therefore we repeat). In this fashion, this works forever.

This would be really hard to do if the condition was something like if the key shift is pressed.