Skip to content

Instantly share code, notes, and snippets.

@sonemaro
Created April 27, 2024 16:53
Show Gist options
  • Save sonemaro/c48939a458ad49c60534707808e08cce to your computer and use it in GitHub Desktop.
Save sonemaro/c48939a458ad49c60534707808e08cce to your computer and use it in GitHub Desktop.
Some mac pro keyboards are broken, this code prevents unnecessary key strokes
from pynput import keyboard
from pynput.keyboard import Key, Controller
import datetime
# --- initialise ---
#global Hotkeys
cmd = False
lastChar = ''
lastTimeChar = datetime.datetime.now()
theSame = False
# ======
def on_press(key):
global cmd
global memory
global theSame
global lastChar
try:
# TODO : add broken keys to an array and check if key.char in array and is the same
nt = datetime.datetime.now()
theSame = getDeltaMiliSec(lastTimeChar, nt) < 100 and key.char == lastChar
# if key.char == lastChar:
# theSame = True
# else:
# theSame = False
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
global lastChar
global lastTimeChar
try:
lastChar = key.char
lastTimeChar = datetime.datetime.now()
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 getDeltaMiliSec(t1, t2):
delta = t2 - t1
return int(delta.total_seconds() * 1000)
def darwin_intercept(event_type, event): # pynput-internal definition
import Quartz
global cmd
global lastTimeChar
global lastChar
global theSame
length, chars = Quartz.CGEventKeyboardGetUnicodeString(
event, 100, None, None)
if cmd == True and length > 0 and chars == 'q': # Apple down + q
return None
elif theSame:
return None
# elif theSame and getDeltaMiliSec(lastTimeChar, nt) <ñ50:
# print(length, chars, getDeltaMiliSec(lastTimeChar, nt))nnansddaan
# 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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment