3

I need to send a key down / key up event for number keys to an application using AppleScript. However, the commands:

key down "6"
delay 1
key up "6"

send the keystrokes as if they were coming from the number pad. I need them to be interpreted as coming from the number row at the top of the keyboard.

I’ve also tried using (ASCII character 54) instead of a literal, without success.

Note I need key down to be sent – sending a keystroke or key code will not do.

kopischke
  • 3,393
  • 1
  • 21
  • 40
monofonik
  • 2,735
  • 3
  • 20
  • 17

2 Answers2

3

Try sending key down the virtual key code instead of a keystroke literal, i.e.

key down (key code <int>)

where int is one of

1 → 18
2 → 19
3 → 20
4 → 21
5 → 23
6 → 22
7 → 26
8 → 28
9 → 25
0 → 29

You will find all virtual key codes declared in

/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h

but if you don’t feel like doing hex to integer conversion, the easiest way to look them up is probably to use Key Codes by Many Tricks, as suggested by dj bazzie wazzie.

Community
  • 1
  • 1
kopischke
  • 3,393
  • 1
  • 21
  • 40
  • 1
    thanks... but that doesn't seem to work. the "key code" command sends the keystroke to the application, however the key up / down component is ignored. – monofonik Jun 07 '12 at 01:20
  • 2
    @monofonik: Indeed - `key up/down` only works as expected with **modifier** keys. While **NON-modifier keys** can be sent (using `(key code )` syntax), the **up / down aspect is ignored**, making both `key down (key code )` and `key up (key code )` statements **effectively the same as `key code `**. – mklement0 Jan 31 '14 at 21:40
  • 4
    Using `key down (key code )`, with any `` causas always `a` to be pressed. Any thoughts? – Cristiano Sousa Feb 15 '14 at 19:21
  • maybe this helps for the "a"-bug: http://stackoverflow.com/questions/25366014/script-auto-correcting-incorrectly-when-i-compile-and-key-down-key-up-not-workin/31909645#31909645 – Snow Aug 09 '15 at 23:08
1

Key down and up won't work when using system events you need key code or keystroke. Keystroke will perform it's value while key code needs the key number. Download the app 'Key Codes' from the app store to determine the correct key codes (it's free).

--activate the application (and it's first responder) first
tell application "System Events"
    keystroke "1" --value "1"
    key code 18 --1 from upper num keys
    key code 83 --1 from num pad
end tell
dj bazzie wazzie
  • 3,472
  • 18
  • 23
  • 1
    Thanks for the answer, but I actually need to press and hold keys, as opposed to just a keystroke. – monofonik May 23 '12 at 11:04
  • 1
    Actually, `key down` and `key up` **will** work, though they are absent from System Event’s AppleScript dictionary (go figure – silent deprecation, maybe). – kopischke May 23 '12 at 11:58