I'm trying to write an applescript which will insert some predefined text at the beginning of a message. This is what I currently have:
set msgClass to (choose from list {"Green", "Blue", "Purple"} with title "Choose:")
if result is false then
stop
else
set msgClasstxt to the result
set msgClasstxt to "Classification: " & msgClasstxt
tell application "System Events"
key code 126 using {command down}
keystroke return
keystroke return
key code 126 using {command down}
end tell
tell application "Microsoft Outlook" to set selection to msgClasstxt
end if
I'm sure there's a better way to do this, but the intent is as follows:
- Go home w/CMD+Up
- Create two empty lines
- Go home again
- Insert text
My problem is that the text is being inserted BEFORE the keystrokes are performed. Vexing. Can anyone help?
Keystrokes and other gui tasks are input to the frontmost application. As such you should always activate the application you want targeted just before performing these actions. Thus I advise you put the following just before your system events code. Even if you think the application is frontmost you should do this anyway just to be certain.
Also, as suggested in other comments you need short delays between each line of gui code to ensure the computer has time to physically perform the code.
So use delays and activate the application. That should help you.