zeth / inputs

Cross-platform Python support for keyboards, mice and gamepads
BSD 3-Clause "New" or "Revised" License
273 stars 88 forks source link

catch KeyboardInterrupt #58

Open frastlin opened 5 years ago

frastlin commented 5 years ago

Hello, Somewhere there needs to be a place that triggers an event for KeyboardInterrupt. This can be done by using a try statement: try: yield event except KeyboardInterrupt: yield KeyboardInterruptEvent

This will help in: https://github.com/zeth/inputs/issues/23#issuecomment-443534823 It is also useful to allow users to block KeyboardInterrupt if they really want (although it should not be default).

frastlin commented 5 years ago

I did some playing around and think I know what needs to be done, I just don't understand the structure of the code well enough to do a PR. KeyboardInterrupt happens in both the main thread and the Process. For the process it is:

def handle_input(self, ncode, wparam, lparam)

Something needs to go in this function catching the KeyboardInterrupt event, similar to what happens in the main thread. In the main thread, the following works pretty well, although I would like to return an KeyboardInterruptEvent object:

def get_key(ignoreKeyboardInterrupt=False):
    """Get a single keypress from a keyboard."""
    try:
        keyboard = devices.keyboards[0]
    except IndexError:
        raise UnpluggedError("No keyboard found.")
    try:
        return keyboard.read()
    except KeyboardInterrupt:
        if not ignoreKeyboardInterrupt:
            raise KeyboardInterrupt
        else:
            return KeyboardInterruptEvent