Search code examples
pythonlistenerpynput

pynput.mouse Listener do not stop


Here is my prank code for my friend but I can not stop this program from keyboard when I make executable.

How can I stop this listener from keyboard shortcut. I know it is thread issue.

import sys
import pyautogui
import keyboard
from pynput.mouse import Listener
from threading import Thread

global x,y

def on_move(x, y):
    print ("Mouse moved to ({0}, {1})".format(x, y))

def on_click(x, y, button, pressed):
    try: #FOR AUTO FAIL-SAFE
        if pressed:
            print ('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))
            pyautogui.move(x+100,y+100)
    except:
        pass

def on_scroll(x, y, dx, dy):
    print ('Mouse scrolled at ({0}, {1})({2}, {3})'.format(x, y, dx, dy))


with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
    listener.join()

while True:
    if keyboard.is_pressed("q"):
        sys.exit(0)
        break

Solution

  • I solved this problem. When mouse position(x,y) on left-top and mid scrolled. Program finishes itself.

    def on_scroll(x, y, dx, dy):
        print('Scrolled {0} at {1}'.format(
        'down' if dy < 0 else 'up',
        (x, y,dx,dy)))
        if x<100 and y<100:
            return False