AppleScript Programming/System Events

One of the many things that can be used with Applescript, is System Events. To use the System Event application, you must first give it a "tell" command.

 tell application "System Events"
   -- add code here.
 end tell

This will tell applescript to execute commands associated with the program System Events. For example, the command:

 keystroke "e"

Will type the letter "e" into the current application.

Here's a simple program:

tell application "TextEdit"
	activate
	make new document
end tell
tell application "System Events"
	keystroke "Support Wikibooks!"
end tell

It will open the application TextEdit, start a new document, and type the phrase "Support Wikibooks!"

You can also use keystroke tab (note that there are no quotes) to type a tab, and keystroke return to enter a new line.

tell application "TextEdit"
	activate
	make new document
end tell
tell application "System Events"
	keystroke "Support Wikibooks!"
	keystroke return
	keystroke "by donating!"
end tell

Which will create a new document with Support Wikibooks! and by donating, on another line.

Now you may be wondering, How do I perform key combinations like command+q (Works with other modifier keys, like option, and control)

Key combos is a three line code consisting of

key down {command}
keystroke "q"
key up {command}

You can also hold down many keys at a time using the augment of key down and key up but separating keys using commas

Here is a program that will open text edit and then quit it using command+q:

tell application "TextEdit"
	activate
end tell

delay 3.0

tell application "System Events"
	key down {command}
	keystroke "q"
	key up {command}
end tell

You can also use one line commands for keystrokes, such as:

tell application "System Events" to keystroke "c" using command down

Which will invoke Copy in most Mac applications.

It is possible to use combokeys in oneline like this:

keystroke "h" using {command down, shift down}