如何在OS X上将进程窗口置于前台?

时间:2016-01-12 14:33:01

标签: macos bash shell window-management

我有一个简单的shell / python脚本,可以打开其他窗口。我希望在脚本完成后将脚本运行的终端带到前台。

我知道父窗口的进程ID。 如何将给定窗口带到前台?我想我必须从中找出PID中的窗口名称。

2 个答案:

答案 0 :(得分:3)

感谢马克的精彩回答! 稍微扩展一下:

# 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
}

然后您可以运行:

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

快速测试使用:

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

换掉别的东西。 5秒后,运行脚本的终端将被发送到顶部。

答案 1 :(得分:2)

不确定是否有正确的方式,但这对我有用:

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

您也可以使用osacript -e '...'执行此操作。

显然将350更改为您想要的pid。