boppreh / keyboard

Hook and simulate global keyboard events on Windows and Linux.
MIT License
3.74k stars 432 forks source link

How to handle quitting from listener loop? #616

Open Coderbeep opened 10 months ago

Coderbeep commented 10 months ago

I want to be able to perform some actions when specified keys are pressed. The code looks like this:

    def handle_keyboard_input(self):
        while True:
            # print("\nCommands: 'n' - Next page, 'N' - Previous page, 'q' - Quit")
            event = keyboard.read_event(suppress=True)

            if event.event_type == keyboard.KEY_DOWN:
                if event.name == 'n':
                    self.move_next()
                elif event.name == 'N':
                    self.move_previous()
                elif event.name == 'q':
                    break

The 'n' and 'N' keys work perfectly, however when 'q' is pressed sometimes the loop does not break and requires multiple q presses to handle the break action. I have found some information about that on stackoverflow. The solution from here is to use keyboard.send('ctrl+c'), but there must be a different way to handle it neatly.

Thanks in advance :)