Detect Modifier Key down

Hi KniazidisR.

I often do listen to Shane’s good advice. :wink: Otherwise the reasons I didn’t and won’t write code like that are given in my discussion with him above. Other people are free to make up their own minds.

In the case of the current handler, which is unlikely to be the only thing in a script, a better compromise would be to write the numbers directly into its code with comments explaining what they mean:

use AppleScript version "2.4" -- The ability to use ASObjC in running scripts was introduced in Mac OS 10.10.
use framework "Foundation"
use framework "AppKit" -- NSEvent is an AppKit class.
use scripting additions -- In case needed.

on modifierKeysPressed()
	set modifierKeysDOWN to {command_down:false, option_down:false, control_down:false, shift_down:false}
	
	set currentModifiers to current application's class "NSEvent"'s modifierFlags()
	tell modifierKeysDOWN
		-- 524288: NSAlternateKeyMask constant in Mac OS 10.10 & 10.11/NSEventModifierFlagOption thereafter.
		set its option_down to (currentModifiers div 524288 mod 2 is 1)
		-- 1048576: NSCommandKeyMask/NSEventModifierFlagCommand.
		set its command_down to (currentModifiers div 1048576 mod 2 is 1)
		-- 131072: NSShiftKeyMask/NSEventModifierFlagShift.
		set its shift_down to (currentModifiers div 131072 mod 2 is 1)
		-- 262144: NSControlKeyMask/NSEventModifierKeyControl.
		set its control_down to (currentModifiers div 262144 mod 2 is 1)
	end tell
	
	return modifierKeysDOWN
end modifierKeysPressed

modifierKeysPressed()

This way you dispense with ludicrous code like a reference to 524288 and with four pointless properties having their values saved back to the script file every time it’s run. At the same time, it’s immediately clear to anyone else trying to debug the larger script later what the numbers are supposed to mean and it won’t be necessary to look back through the script to see if or where NSEventModifierFlagOption has been set as a variable and whether or not its use without current application’s in front of it is deliberate or a typo.