Focus most recent window of pid without requiring accessibility approval

applescriptcocoa

I currently use this AppleScript to try to set focus to the most recent window of a PID, in example here my pid is 450.

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

This works wonderfully in that it doesn't ask for accessibility approval. The quirks though are:

  • It ignores minimized windows, thus if all windows are minimized, nothing is focused
  • If you have windows across multiple spaces, and last accessed window was in space X. If you are in space Y and have windows of that app in space Y, it will focus the most recently used in space Y.
  • I haven't encountered it yet, but apparently people say if a window of other applications are on top of the window, it won't come to top.

I know of perform action AXRaise however this needs accessibility api approval. My users of my addon are asking to remove this as many of them struggle with allowing the single app access, especially if the miss granting it on the first popup.

So this was done in applescript, if you know how to do it in carbon (core-foundation, core-graphics) or cocoa I can use that to.

In osx 10.9 the AXMakeProcessTrusted was deprecated otherwise I could have used that to grant my app access without bothering users and then use AXUIElementSetAttributeValue to bring a window to the front.

Please help
Thanks

Best Answer

This fixes the first quirk but not the second one:

tell application "System Events"
    bundle identifier of process 1 whose id is 1234
end tell
tell application id result
    reopen
    activate
end tell

The same applies to open:

open -a "$(ps -p 1234 -o comm=)"

If there are no open windows, reopen opens a new default window, and if all windows are minimized, reopen unminimizes one window. activate makes the application frontmost.

activate and setting frontmost to true raise all windows but open -a only raises one window.

I thought

lsappinfo launch ASN="$(lsappinfo find pid=1234)"

might also work, but I'm getting a segfault when trying to launch an already running application.