Auto Typer onto Unfocused Application
System Events can only send a keystroke to the front most application or its window.

However, if you want to send a text message to a Buddy using Messages, while it's in the background, the following example AppleScript code works for me:

set targetBuddy to "+nnnnnnnnnnn"
set textMessage to "Hello World!"

tell application "Messages"
    set targetService to id of 1st service whose service type = iMessage
    set theBuddy to buddy targetBuddy of service id targetService
    send textMessage to theBuddy
end tell



The "+nnnnnnnnnnn" in set targetBuddy to represents the Buddy's phone number. Also, as coded, Messages is already opened and in the background. Otherwise additional code is required.




Note: The example AppleScript code is just that and does not contain any error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors.