Search code examples
pythonpyautogui

Custom trigger to execute failsafe in pyautogui


The default trigger of failsafe pyautogui is drag mouse to up-left corner. if i do that then the program will stop. How to change trigger, instead drag mouse i want set the trigger with keyboard input. for example if i press P key then the program will stop (the failsafe executed)


Solution

  • There isnt a way using pyautogui but it has been done using pynput. here is an example (pay attention to def keypress specifiaclly)

    from random import random
    from threading import Thread
    from time import sleep
    
    from pynput.mouse import Controller, Button
    from pynput.keyboard import KeyCode, Listener
    import pyautogui
    
    delay = float(pyautogui.confirm(text='Choose Clicking Speed Per Second', title='Spook AutoClicker', buttons=['0.5','0.001']))
    
    mouse = Controller()
    
    
    class AutoClicker(Thread):
        clicking = False
    
        def run(self):
            while True:
                if AutoClicker.clicking:
                    mouse.click(Button.left)
                sleep(delay)
    
    
    def keypress(key):
        if key == KeyCode(char="p"):
            AutoClicker.clicking = not AutoClicker.clicking
    
    
    AutoClicker().start()
    
    with Listener(on_press=keypress) as listener:
        listener.join()