I need to get a list of keys (e.g. the shift key, alt, command ...) which have been pressed when i started an app, especially an ApplesScript on Mac OS X.
A shorter form of Mike Woodfill's answer:
set {shiftDown, ctrlDown, altDown, cmdDown} to words of (do shell script "python -c 'import Cocoa;m=Cocoa.NSEvent.modifierFlags();print m&Cocoa.NSShiftKeyMask>0,m&Cocoa.NSControlKeyMask>0,m&Cocoa.NSAlternateKeyMask>0,m&Cocoa.NSCommandKeyMask>0'")
Note, that you get the modifiers as strings, so you have to compare them like this if (altDown = "True") then ...
If you really want boolean modifiers, look at this code:
set mods to {}
repeat with m in words of (do shell script "python -c 'import Cocoa;m=Cocoa.NSEvent.modifierFlags();print m&Cocoa.NSShiftKeyMask,m&Cocoa.NSControlKeyMask,m&Cocoa.NSAlternateKeyMask,m&Cocoa.NSCommandKeyMask'")
set end of mods to m as number as boolean
end repeat
set {shiftDown, ctrlDown, altDown, cmdDown} to mods
See post #5 by StefanK at MacScripter / Tiger shiftKey detect error. He wrote a command line tool called checkModifierKeys which may be what you need. The code is posted too so you can adjust it if needed.
You can use the following code to detect is modifier keys are being held down using "vanilla" applescript.
on isModifierKeyPressed()
set modiferKeysDOWN to {command_down:false, option_down:false, control_down:false, shift_down:false}
if (do shell script "/usr/bin/python -c 'import Cocoa; print Cocoa.NSEvent.modifierFlags() & Cocoa.NSAlternateKeyMask '") > 1 then
set option_down of modiferKeysDOWN to true
end if
if (do shell script "/usr/bin/python -c 'import Cocoa; print Cocoa.NSEvent.modifierFlags() & Cocoa.NSCommandKeyMask '") > 1 then
set command_down of modiferKeysDOWN to true
end if
if (do shell script "/usr/bin/python -c 'import Cocoa; print Cocoa.NSEvent.modifierFlags() & Cocoa.NSShiftKeyMask '") > 1 then
set shift_down of modiferKeysDOWN to true
end if
if (do shell script "/usr/bin/python -c 'import Cocoa; print Cocoa.NSEvent.modifierFlags() & Cocoa. NSControlKeyMask '") > 1 then
set control_down of modiferKeysDOWN to true
end if
return modiferKeysDOWN
end isModifierKeyPressed
来源:https://stackoverflow.com/questions/7514280/get-modifier-keys-which-have-been-pressed-while-starting-an-app-applescript