How do I bring a processes window to the foreground on OS X?

巧了我就是萌 提交于 2019-12-02 01:29:33

Not sure if there's a proper way, but this works for me:

osascript<<EOF
tell application "System Events"
    set processList to every process whose unix id is 350
    repeat with proc in processList
        set the frontmost of proc to true
    end repeat
end tell
EOF

You can do it with osacript -e '...' too.

Obviously change the 350 to the pid you want.

Thanks to Mark for his awesome answer! Expanding on that a little:

# Look up the parent of the given PID.
# From http://stackoverflow.com/questions/3586888/how-do-i-find-the-top-level-parent-pid-of-a-given-process-using-bash
function get-top-parent-pid () {
    PID=${1:-$$}
    PARENT=$(ps -p $PID -o ppid=)

    # /sbin/init always has a PID of 1, so if you reach that, the current PID is
    # the top-level parent. Otherwise, keep looking.
    if [[ ${PARENT} -eq 1 ]] ; then
        echo ${PID}
    else
        get-top-parent-pid ${PARENT}
    fi
}

function bring-window-to-top () {
    osascript<<EOF
    tell application "System Events"
        set processList to every process whose unix id is ${1}
        repeat with proc in processList
            set the frontmost of proc to true
        end repeat
    end tell
EOF
}

You can then run:

bring-window-to-top $(get-top-parent-pid)

Quick test using:

sleep 5; bring-window-to-top $(get-top-parent-pid)

And swap to something else. After 5 seconds the terminal running your script will be sent to the top.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!