Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send key down / up events for number keys using AppleScript

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.

like image 927
monofonik Avatar asked Jan 29 '26 12:01

monofonik


2 Answers

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.

like image 151
kopischke Avatar answered Jan 31 '26 02:01

kopischke


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
like image 36
dj bazzie wazzie Avatar answered Jan 31 '26 02:01

dj bazzie wazzie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!