Apple - AppleScript keystroke ignoring numbers

Have a look at https://stackoverflow.com/questions/18136567/applescript-keystroke-not-behaving-as-expected & the list of ANSI codes at How do I automate a key press in AppleScript?

It appears you're not the only one with the issue. One solution on there was to use the key code instead...

tell application "System Events"
    key code {18} using {command down}

It may depend on what app you're trying to send the keystrokes to - I just tested with an already-open blank document in Text Edit using

tell application "TextEdit" to activate
tell application "System Events"
    keystroke "abc 123"
end tell

& it worked as expected.

A keystroke is the scripted equivalent of actually pressing that/those keys[s]

How about...

tell application "TextEdit" to activate
tell application "System Events"
    keystroke "abc"
    keystroke space
    keystroke "123"
end tell

Some more info about this issue that I've discovered is that when using keystroke with numbers, the System Events always sends them as ANSI_Keypad# characters (code 82-92) instead of what you might expect as ANSI_# characters (code 18-29).

For most Mac applications, this does not matter as OS X itself does not care about (use, support, etc) the NUMLOCK function on a Keypad, therefore the Keypad numbers are seen the same as keyboard numbers. However, it will pass the NUMLOCK keypress to the application if you have a keyboard/keypad that has this key.

There are a few applications that do monitor the NUMLOCK key (for example, VMware Fusion application when running a Windows VM) and will change the behavior based on the NUMLOCK state.

So for example, if the AppleScript sends keystroke "456" to a NUMLOCK aware application.

  • If the NUMLOCK state is ON, the numbers "456" will appear.
  • If the NUMLOCK state is OFF, the equivalent keys received are Left Arrow 5 Right Arrow

In the original question, the AppleScript sent abc 123 but most likely his application (which was not mentioned) was aware of the NUMLOCK state, which was currently OFF, and therefore executed the keys as abc [space] End Down Arrow Page Down

I put together a little AppleScript function that loops through the given string sending key code commands for any numbers and keystroke commands for any other characters.

on numberAsKeycode(theString)
  tell application "System Events"
    repeat with currentChar in (every character of theString)
      set cID to id of currentChar
      if ((cID ≥ 48) and (cID ≤ 57)) then
        key code {item (cID - 47) of {29, 18, 19, 20, 21, 23, 22, 26, 28, 25}}
      else
        keystroke currentChar
      end if
    end repeat
  end tell
end numberAsKeycode

set myString to "abc 123"
numberAsKeycode(myString)

Which executes the following

tell application "System Events"
  keystroke "a"
  keystroke "b"
  keystroke "c"
  keystroke " "
  key code {18}
  key code {19}
  key code {20}
end tell

Hope this helps :)