How to use Applescript to type in a application?

I'm trying to type in another application using Applescript, and it keeps giving me this error: Can't get keystroke of "string".

This is my code.

on run {}
    tell application "My Application"
        set str to "string"
        repeat
            keystroke str
            keystroke return
            delay (random number from 5.0 to 10.0)
        end repeat
    end tell
end run

Also, when I replace application with process, it types into the Script Editor instead of the desired application. It would be preferred if I use the application name instead of it's process ID, otherwise I'd have to change the Process ID variable every time.


Solution 1:

You need to use System Events to send the keystrokes not the app, try something like this:

on run {}
    tell application "My Application" to activate
    set str to "string"
    repeat
        tell application "System Events" to keystroke str
        tell application "System Events" to keystroke return
        delay (random number from 5.0 to 10.0)
    end repeat
end run