Observations as of OS X 10.9.1:
There's a problem with the way you're sending F2
(you need to use (key code 120)
instead of just 120
), but the larger problem is that key up/down
only works as expected with modifier keys.
While NON-modifier keys can be sent (using (key code <n>)
syntax), the up / down aspect is ignored, making both key down (key code <n>)
and key up (key code <n>)
statements effectively the same as key code <n>
(i.e., a Key Down
event immediately followed by a Key Up
event is sent).
There's a suggested workaround here, based on repeatedly sending keystrokes in short sequence - it's worth a try, but from a technical perspective it's not the same as keeping a key [combination] held down, so I'm not sure it'll work.
Adapted to your situation (and replacing key down
with key code
), we get:
tell application "System Events"
set now to the seconds of the (current date)
set later to now + 5
if later > 60 then set later to later - 60
key down command
# Workaround: send F2 repeatedly.
repeat while the seconds of the (current date) is not later
key code 120
end repeat
key up command
end tell
As I said: this may not work; also note that the loop is "tight" meaning that it'll make your machine pretty busy (if sending keys repeatedly, but not necessarily as fast as possible is an option, you could insert a short delay
).
Some optional background info:
- The
key up
and key down
commands, while also requiring the System Events
context, are NOT exposed in the System Events.sdef
, the app's dictionary (only key code
and keystroke
are listed) - this may indicate that Apple doesn't officially support them.
- On OS X 10.9.1 (unlike on OS X 10.8 - don't know about earlier versions) there is a bizarre bug where an extra "a" keypress is sent whenever you use
key down
with a (keycode <n>)
specifier.
- Ways of determining key-code values (gleaned from various other SO answers, mostly here):
- Key Codes, a free GUI app for interactive use - very handy.
- The following header file on your system (list of codes in hex format):
/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h
- List of decimal codes (incomplete):