Inserting Text at the Beginning of a Message

431 Views Asked by At

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?

2

There are 2 best solutions below

2
regulus6633 On

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.

tell application "Microsoft Outlook" to activate
delay 0.2

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.

2
jpdyson On

So, this is what I've done: -Added a provision to make sure I'm dealing with the currently-active message window -Activate that window -Done all actions via system events

tell application "Microsoft Outlook" to get the id of the first window
set currentWindow to the result

set msgClass to (choose from list {"Green", "Blue", "Purple"} with title "Choose:")

if the result is false then
    stop
else
    set msgClasstxt to "Classification: " & the result
    tell application "Microsoft Outlook"
        activate window currentWindow
        tell application "System Events"
            key code 126 using {command down}
            keystroke return
            keystroke return
            key code 126 using {command down}
            keystroke msgClasstxt
        end tell
    end tell
end if

That first line works because Outlook lists the frontmost window first. This does what I want for now.