How to suppress function keys in macOS / Quartz / pynput?

272 Views Asked by At

The example given in the pynput documentation is:

def darwin_intercept(event_type, event):
    import Quartz
    length, chars = Quartz.CGEventKeyboardGetUnicodeString(
        event, 100, None, None)
    if length > 0 and chars == 'x':
        # Suppress x
        return None
    else:
        return event

But how to suppress function keys, e.g., the control key (who doesn't have an Unicode equivalent)? I tried simply replacing chars == 'x' by virtualKey == 0x37, but got an error message...

1

There are 1 best solutions below

1
On

This seems to do the trick:

from pynput import keyboard
from pynput.keyboard import Key, Controller
# --- initialise ---
#global Hotkeys
cmd = False
# ======
def on_press(key):
    global cmd
    global memory
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
        # ...   
    except AttributeError:
        print('special key {0} pressed'.format(
            key))
        if key == Key.cmd:
            cmd = True
            # (modifier) # Windows key / MacOS Command key  
        # ...
# ======
def on_release(key):
    global cmd
    try:
        print('{0} released'.format(
            key))
        if key == keyboard.Key.esc:                             # <--- stop program
            # Stop listener
            return False
        elif key == Key.cmd:                                    # Win up # Apple up
            cmd = False
            # (modifier) # Windows key / MacOS Command key
    except AttributeError:
        print('on_release special key {0} released'.format(
            key)) # Am Ende löschen
        # nothing
# ======
def darwin_intercept(event_type, event):                        # pynput-internal definition
    import Quartz
    global cmd
    length, chars = Quartz.CGEventKeyboardGetUnicodeString(
        event, 100, None, None)
    if cmd == True and length > 0 and chars == 'q':             # Apple down + q
        return None
    else:
        return event
# ======
# Collect events until released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release,
        # Add suppressing events (darwin_intercept):
        darwin_intercept=darwin_intercept) as listener:
    listener.join()