How can one invoke a keyboard shortcut from within an AppleScript?

Barton picture Barton · Sep 11, 2010 · Viewed 32k times · Source

I need to invoke a keyboard shortcut from within an AppleScript code, e.g. Cmd+Ctrl+Opt+E.

Answer

regulus6633 picture regulus6633 · Sep 13, 2010

Sure it works. System events can perform keystrokes. However, keystrokes are always sent to the frontmost application so to perform a shortcut for an application you must tell that app to activate first and then perform the shortcut. For example, I can open a new tab in Safari using command-t. That applescript would look like this...

tell application "Safari" to activate
tell application "System Events"
    keystroke "t" using command down
end tell

Now suppose you have a global keyboard shortcut. Global meaning it works from any application. Then you don't even need to activate an application first, just perform the keystroke. To press the keys you requested do this...

tell application "System Events"
    keystroke "e" using {command down, option down, control down}
end tell