Mark
Mark

Reputation: 2435

Bring application to front by ID

I want to use AppleScript to bring an app to the front. If I run the following script

tell application "System Events"
  tell process id 916
    activate
  end tell
end tell

the process doesn't come to front. Instead, only the active window of the currently front-most app loses focus, but that app stays in front.

Is it even possible to do this with a process ID rather than an application name? I have tried this on Mac OS X 10.6.8 and 10.7.5.

I am looking for a plain AppleScript solution. It should not use any shell commands or any other solution. I want to use the process ID number because I might have running multiple instances of the same application (in the same file location).

Upvotes: 1

Views: 2799

Answers (3)

Devon
Devon

Reputation: 1093

The correct answer is at https://stackoverflow.com/a/22951788/3008405 for example,

tell application "System Events"
  set frontmost of the first process whose unix id is 123 to true
  end tell

or a complete example,

tell application "System Events"
  set PID to unix id of first process whose frontmost is true
  activate
  log choose from list {"Foo", "Bar"} with prompt "Prompt" with title "Title"
  set frontmost of the first process whose unix id is PID to true
  end tell

the initial set saves the PID, the final set restores it to frontmost.

Non-PID solutions fail when there are multiple instances of the same app.

Upvotes: -1

Mark
Mark

Reputation: 2435

I have found the following solution:

tell application "System Events"
    set myProcesses to every process whose unix id is myPocessID
    repeat with myProcess in myProcesses
        set the frontmost of myProcess to true
    end repeat
end tell

Foo's answer works too:

tell application "System Events"
    set frontmost of every process whose unix id is myProcessID to true
end tell

Upvotes: 3

CRGreen
CRGreen

Reputation: 3429

set processID to 432--currently firefox for me
tell application "System Events" to set a to file of 1st item of (processes whose unix id = processID)
activate application (a as alias as string)

This uses the path to the app file, which is apparently necessary (not just the name). I have another answer which uses do shell script; I could add that if you want.

Upvotes: 1

Related Questions