boppreh / keyboard

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

hotkey does not be suppressed when the callback returns True #596

Closed DukSon1224 closed 1 year ago

DukSon1224 commented 1 year ago

As the title, if the callback returns True, then hotkey does not be suppressed.

Next is an example code.

import keyboard

def callback1(*argv):
    print(*argv)
    return True

def callback2(*argv):
    print(*argv)
    return False

def callback3(*argv):
    print(*argv)
    return None

keyboard.add_hotkey("1", callback1, args=["1"], suppress=True)
keyboard.add_hotkey("2", callback2, args=["2"], suppress=True)
keyboard.add_hotkey("3", callback3, args=["3"], suppress=True)
keyboard.wait("esc")

Test it on something like notepad. 2 or 3 cannot be typed, but 1 can be. I don't know it is intended or not, I cannot find information about this.

Cover the callback, then it can be work well.

import keyboard

def callback1(*argv):
    print(*argv)
    return True

def cover(callback, *argv):
    callback(*argv)
    return None

# use covering
keyboard.add_hotkey("1", cover, args=[callback1, "1"], suppress=True)
# or use lambda
keyboard.add_hotkey(
    "2",
    lambda callback, *argv: None if callback(*argv) else None,
    args=[callback1, "2"],
    suppress=True,
)
keyboard.wait("esc")

Usually you don't need to use it like this, but if you need to use a function always returns True like the emit method of signal of pyside or pyqt, covering makes hotkey be suppressed.