moses-palmer / pynput

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

Not able to terminate the program #460

Closed Shreysid closed 2 years ago

Shreysid commented 2 years ago

Description Not able to stop the program using the binding keys given to terminate it

Platform and pynput version using the jupyter extension, version v2022.2.1030672458 in visual studio code version 1.65.2 on m1 mac, the pynput version being 1.7.6

To Reproduce

#importing libraries
import time
import threading
from pynput.mouse import Button, Controller
from pynput.keyboard import Listener, KeyCode

#key binding
delay = 0.001
button = Button.left
start_stop_key = KeyCode(char='s')
exit_key = KeyCode(char='e')

class ClickMouse(threading.Thread):
    def __init__(self, delay, button):
        super(ClickMouse, self).__init__()
        self.delay = delay
        self.button = button
        self.running = False
        self.program_running = True

    def start_clicking(self):
        self.running = True

    def stop_clicking(self):
        self.running = False

    def exit(self):
        self.stop_clicking()
        self.program_running = False

    def run(self):
        while self.program_running:
            while self.running:
                mouse.position = (751, 484)
                mouse.press(Button.left)
                mouse.release(Button.left)
                mouse.position = (474, 786)
                mouse.press(Button.left)
                mouse.release(Button.left)
                mouse.position = (875, 786)
                mouse.press(Button.left)
                mouse.release(Button.left)
                mouse.position = (1341, 456)
                mouse.press(Button.left)
                mouse.release(Button.left)
            time.sleep(2)

mouse = Controller()
click_thread = ClickMouse(delay, button)
click_thread.start()

def on_press(key):
    if key == start_stop_key:
        if click_thread.running:
            click_thread.stop_clicking()
        else:
            click_thread.start_clicking()
    elif key == exit_key:
        click_thread.exit()
        listener.stop()

with Listener(on_press=on_press) as listener:
    listener.join()
IGalat commented 2 years ago

@Shreysid , Try comparing vk codes with ==, that is start_stop_key.vk_code == key.vk_code

Alternatively, try this hotkey util

moses-palmer commented 2 years ago

Thank you for your report.

As @IGalat notes, I suspect that the comparison in on_press is the issue. From your code, I gather that you want to detect when E or S are pressed. For this, I suggest using key.char instead.

Please note that this attribute is not necessarily present---special keys do not have it---so you will need to check that first.