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

十年热恋 提交于 2019-12-02 01:45:56

问题


I have a simple shell/python script that opens up other windows. I'd like to bring the terminal where the script is running to the foreground when the script has finished.

I know the process ID of my parent window. How can I bring a given window to the foreground? I imagine I have to find out the window name from the PID along the way.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/34746399/how-do-i-bring-a-processes-window-to-the-foreground-on-os-x

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