34

I'm trying to write an Applescript in Automator that will press the left arrow button while holding down control, option, and command. The code I have so far is:

on run {input, parameters}

    tell application "System Events"
        tell application "Sublime Text 2" to activate
        keystroke "left" using {control down, option down, command down}
    end tell

    return input
end run

However, this is not working. Any suggestions as to how to fix this code? Thanks!

Digital Trauma
  • 15,475
  • 3
  • 51
  • 83
  • did u try to map the home and end button on the keyboard to map with command + right or left ? – bicepjai Dec 16 '14 at 08:29
  • FYI: What this is actually doing is attempting to type the word "left" with all three modifiers down. – cabbey Mar 29 '16 at 19:26

2 Answers2

62

When using arrow keys you need to target them via key code.

tell application "Sublime Text 2" to activate

tell application "System Events" 
    key code 123 using {control down, option down, command down}
end tell

ARROW KEY CODES

  • LEFT: (key code 123)
  • RIGHT: key code 124)
  • UP: (key code 126)
  • DOWN: (key code 125)
adamh
  • 3,222
  • 1
  • 20
  • 16
5

You can use any ASCII code, for the arrow keys this will be:

tell application "System Events" to keystroke (ASCII character 31) --down arrow

tell application "System Events" to keystroke (ASCII character 30) --up arrow

tell application "System Events" to keystroke (ASCII character 29) --right arrow

tell application "System Events" to keystroke (ASCII character 28) --left arrow

Links:

Linkmichiel
  • 2,110
  • 4
  • 23
  • 27
  • Those are AppleScript KEY CODES, not ASCII, nor is that confused second link. See https://apple.stackexchange.com/questions/36943/how-do-i-automate-a-key-press-in-applescript#36947 – Devon Jun 02 '20 at 05:14
  • 1
    No, they are ASCII indeed, if you read further after clicking on the first link, you'll see the advice to use the international keystroke versions of the key codes. – Linkmichiel Jun 27 '20 at 06:35
  • Please check reliable references (or even Wikipedia) before repeating misinformation. The Apple community discussion reply by Koenig gives KEY CODES but erroneously calls them ASCII codes. The second link similarly mis-names IBM437 codes. – Devon Jun 28 '20 at 21:32
  • 1
    Misinformation? You might just have to be a bit more careful using such sharp words. The AppleScript Language Guide itself talks of **ASCII character**. As a command, That being said, the **ASCII character command** was deprecated in AppleScript 2. None the least because the command uses the user’s language preferences to map between integers and characters. So let’s not use ASCII character any more. It’s not for 2020+. – Linkmichiel Jun 30 '20 at 21:53