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

3

我有一个简单的shell/python脚本,可以打开其他窗口。 当脚本完成时,我想将运行脚本的终端窗口放到前台。

我知道我的父窗口的进程ID。 如何将指定的窗口置于前台? 我想我需要通过PID找到窗口名称。


我认为你没有窗口的进程与 Terminal.app 的主窗口无关。也许你可以找到一种方法,在不受命令行程序影响的情况下,使 Terminal 获得焦点。 - Nicolas Miari
我相信在桌面Cocoa中有这样的API;只是想不起来了。 - Nicolas Miari
1
@NicolasMiari 我的无窗口进程是终端应用程序的子进程。 - mikemaccana
2个回答

4

不确定是否有“正式”的方法,但这种方法对我有效:

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

你也可以使用 osascript -e '...' 来完成。

显然,将 350 更改为所需的 pid。


3
感谢Mark提供的精彩答案!稍微扩展一下:
# Look up the parent of the given PID.
# From https://dev59.com/GHA65IYBdhLWcg3w4CwL
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
干得好 - 谢谢你与社区分享你的努力 :-) - Mark Setchell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接