Skip to content

Instantly share code, notes, and snippets.

@brunerd

brunerd/keyDown.sh

Last active May 1, 2021
Embed
What would you like to do?
Getting macOS Modifier Key Down Events in JXA and Python
#!/bin/bash
#https://gist.github.com/brunerd/d775ab7b362b72d9feb0c4035f922ede
function printState
{
echo commandKeyDown: $commandKeyDown
echo controlKeyDown: $controlKeyDown
echo optionKeyDown: $optionKeyDown
echo shiftKeyDown: $shiftKeyDown
echo functionKeyDown: $functionKeyDown
echo
}
echo "JXA New Constants (Fastest)"
#returns "true" or "false" if key is held down
commandKeyDown=$(osascript -l JavaScript -e "ObjC.import('Cocoa'); ($.NSEvent.modifierFlags & $.NSEventModifierFlagCommand) > 1")
controlKeyDown=$(osascript -l JavaScript -e "ObjC.import('Cocoa'); ($.NSEvent.modifierFlags & $.NSEventModifierFlagControl) > 1")
optionKeyDown=$(osascript -l JavaScript -e "ObjC.import('Cocoa'); ($.NSEvent.modifierFlags & $.NSEventModifierFlagOption) > 1")
shiftKeyDown=$(osascript -l JavaScript -e "ObjC.import('Cocoa'); ($.NSEvent.modifierFlags & $.NSEventModifierFlagShift) > 1")
functionKeyDown=$(osascript -l JavaScript -e "ObjC.import('Cocoa'); ($.NSEvent.modifierFlags & $.NSEventModifierFlagFunction) > 1")
printState
echo JXA Old Constants
#returns "true" or "false" if key is held down - [DEPRECATED] constants (https://developer.apple.com/documentation/appkit/nscommandkeymask?language=occ)
commandKeyDown=$(osascript -l JavaScript -e "ObjC.import('Cocoa'); ($.NSEvent.modifierFlags & $.NSCommandKeyMask) > 1")
controlKeyDown=$(osascript -l JavaScript -e "ObjC.import('Cocoa'); ($.NSEvent.modifierFlags & $.NSControlKeyMask) > 1")
optionKeyDown=$(osascript -l JavaScript -e "ObjC.import('Cocoa'); ($.NSEvent.modifierFlags & $.NSAlternateKeyMask) > 1")
shiftKeyDown=$(osascript -l JavaScript -e "ObjC.import('Cocoa'); ($.NSEvent.modifierFlags & $.NSShiftKeyMask) > 1")
functionKeyDown=$(osascript -l JavaScript -e "ObjC.import('Cocoa'); ($.NSEvent.modifierFlags & $.NSFunctionKeyMask) > 1")
printState
echo "Python (2x slower)"
#returns string "True" or "False" if key is held down
commandKeyDown=$(/usr/bin/python -c 'import Cocoa; print Cocoa.NSEvent.modifierFlags() & Cocoa.NSCommandKeyMask > 1')
controlKeyDown=$(/usr/bin/python -c 'import Cocoa; print Cocoa.NSEvent.modifierFlags() & Cocoa.NSControlKeyMask > 1')
optionKeyDown=$(/usr/bin/python -c 'import Cocoa; print Cocoa.NSEvent.modifierFlags() & Cocoa.NSAlternateKeyMask > 1')
shiftKeyDown=$(/usr/bin/python -c 'import Cocoa; print Cocoa.NSEvent.modifierFlags() & Cocoa.NSShiftKeyMask > 1')
functionKeyDown=$(/usr/bin/python -c 'import Cocoa; print Cocoa.NSEvent.modifierFlags() & Cocoa.NSFunctionKeyMask > 1')
printState
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment