Send a key code to an application without activating it first?

devin_s picture devin_s · Feb 14, 2011 · Viewed 11.7k times · Source

I'm trying to send the spacebar key to an application without activating it first. The following code almost does what I want but it brings the application to the foreground first.

tell application "X"
    activate
    tell application "System Events" to key code 49
end tell

Answer

Hacker picture Hacker · May 12, 2013

I don't think you can send a keystroke to an inactive application, but you can hide an app immediately after activating it and executing code for it. This does however, cause the app to briefly flash before it hides.

tell application "System Events"
    tell application "X" to activate
    key code 49
    set visible of process "X" to false
end tell