You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否用AppleScript检测屏幕是否有窗口?Bash脚本需求咨询

使用AppleScript检测屏幕窗口状态

当然可以!AppleScript完全能搞定这个需求,而且能轻松和你的bash脚本结合起来用。咱们分两部分来实现:先检测屏幕上是否有任何可见窗口,再搞定你提到的额外需求——检测是否存在活动窗口(当前聚焦的窗口)。

一、检测屏幕是否存在任何可见窗口

这段AppleScript会遍历系统中所有运行的进程,检查每个进程是否可见且拥有窗口,只要找到符合条件的就会返回true:

tell application "System Events"
    set hasVisibleWindows to false
    repeat with proc in every process
        if visible of proc is true and (count of windows of proc) > 0 then
            set hasVisibleWindows to true
            exit repeat
        end if
    end repeat
    return hasVisibleWindows
end tell

在bash脚本里调用非常简单,用osascript命令执行即可:

has_windows=$(osascript -e 'tell application "System Events" set hasVisibleWindows to false repeat with proc in every process if visible of proc is true and (count of windows of proc) > 0 then set hasVisibleWindows to true exit repeat end if end repeat return hasVisibleWindows end tell')

if [ "$has_windows" = "true" ]; then
    echo "屏幕上存在可见窗口"
else
    echo "屏幕上没有任何可见窗口"
fi

二、额外需求:检测是否存在活动窗口

如果需要进一步判断当前是否有处于聚焦状态的活动窗口,可以用这段脚本:

tell application "System Events"
    set activeWindowExists to exists (first window of (first process whose frontmost is true) where visible is true)
    return activeWindowExists
end tell

对应的bash调用示例:

has_active_window=$(osascript -e 'tell application "System Events" set activeWindowExists to exists (first window of (first process whose frontmost is true) where visible is true) return activeWindowExists end tell')

if [ "$has_active_window" = "true" ]; then
    echo "存在活动窗口"
else
    echo "没有活动窗口(或当前前台应用无可见窗口)"
fi

三、整合两个检测的bash脚本示例

要是你想一次完成两种检测,直接把逻辑整合到一个bash脚本里就行:

#!/bin/bash

# 检测是否有可见窗口
has_windows=$(osascript -e 'tell application "System Events" set hasVisibleWindows to false repeat with proc in every process if visible of proc is true and (count of windows of proc) > 0 then set hasVisibleWindows to true exit repeat end if end repeat return hasVisibleWindows end tell')

# 检测是否有活动窗口
has_active_window=$(osascript -e 'tell application "System Events" set activeWindowExists to exists (first window of (first process whose frontmost is true) where visible is true) return activeWindowExists end tell')

echo "屏幕窗口状态检测结果:"
if [ "$has_windows" = "true" ]; then
    echo "- 存在可见窗口"
    if [ "$has_active_window" = "true" ]; then
        echo "- 存在活动窗口"
    else
        echo "- 无活动窗口"
    fi
else
    echo "- 无任何可见窗口"
fi

这个脚本会清晰输出当前屏幕的窗口状态,完全满足你的需求~

内容的提问来源于stack exchange,提问作者Utku Birkan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:41:04