applescript 可通过 bundle id 精确控制 macos 应用窗口位置、尺寸与层级,需处理多屏、全屏、最小化等状态并使用 system events 实现稳定布局自动化。
applescript 可以精确控制 macos 应用窗口的位置、尺寸和层级,配合 system events 实现可靠的窗口布局自动化。关键在于准确获取目标应用、识别窗口、设置坐标与大小,并处理多显示器、全屏、最小化等边界情况。
获取并激活目标应用窗口
先确保应用已运行,再获取其主窗口。推荐使用 bundle identifier 而非名称,避免本地化问题:
- tell application id "com.apple.Safari" to activate
- delay 0.2 — 给界面渲染留出时间
-
tell application "System Events" to tell process "Safari"
set frontWindow to window 1
set position of frontWindow to {0, 0}
set size of frontWindow to {1280, 720}
end tell
适配多显示器与安全区域
macOS 的 bounds of screen 提供当前主屏或指定屏的可用区域(排除菜单栏、Dock)。使用前需确认屏幕索引:
-
tell application "System Events"
set mainScreenBounds to bounds of first screen
-- 返回 {x, y, width, height},如 {0, 0, 1680, 1050}
end tell - 若需定位到第二屏,改用 second screen;注意部分 App(如 Finder)可能有多个窗口,用 first window whose subrole is "AXStandardWindow" 更稳妥
处理常见状态:全屏、最小化、无响应
直接设置 position/size 对全屏或最小化窗口无效,需先还原:
-
if value of attribute "AXFullScreen" of frontWindow is true then
perform action "AXZoom" of frontWindow
end if -
if value of attribute "AXMinimized" of frontWindow is true then
set value of attribute "AXMinimized" of frontWindow to false
end if - 加 timeout 3 包裹关键操作,防止因 App 未就绪卡死脚本
封装为可复用函数(示例:四分之一屏布局)
将常用布局逻辑抽象为 handler,便于组合调用:
-
on placeWindowInQuadrant(appID, quadrant)
tell application id appID to activate
delay 0.3
tell application "System Events" to tell process (name of application id appID)
set w to first window
perform action "AXZoom" of w -- 还原窗口
set b to bounds of first screen
set {x, y, wW, wH} to b
if quadrant is "top-left" then set pos to {x, y} & {wW / 2, wH / 2}
if quadrant is "bottom-right" then set pos to {x + wW / 2, y + wH / 2} & {wW / 2, wH / 2}
set position of w to items 1 thru 2 of pos
set size of w to items 3 thru 4 of pos
end tell
end placeWindowInQuadrant - 调用:placeWindowInQuadrant("com.apple.Safari", "top-left")
不复杂但容易忽略:始终用 bundle ID 启动应用,检查窗口是否存在再操作,对全屏/最小化状态做预处理,多显示器下显式指定 screen 索引。这些细节决定脚本在不同 Mac 上是否稳定生效。











