applescript无法直接最大化窗口,但可通过模拟快捷键(如⌃⌥⌘↑)或设置bounds实现等效效果,需提前启用辅助功能权限并确保目标应用前台激活。

AppleScript 本身不能直接“最大化”窗口(macOS 没有标准的 maximize 命令),但可通过模拟系统快捷键或设置窗口 bounds 实现等效效果。关键在于区分「全屏」、「缩放至屏幕区域」和「还原至可最大化状态并触发缩放」三种常见需求,且必须提前启用辅助功能权限。
确保辅助功能权限已开启
前往「系统设置 → 辅助功能 → 旁白与控制 → 键盘」,勾选「启用快捷键」;再进入「辅助功能 → 隐私 → 辅助功能」,确认「脚本编辑器」和「终端」已授权。
用快捷键触发原生缩放(推荐,兼容性好)
macOS 内置的 ⌃⌥⌘→(右半屏)、⌃⌥⌘←(左半屏)、⌃⌥⌘↑(全屏)等组合键由窗口管理器统一响应,AppleScript 可稳定模拟:
tell application "System Events"
key code 126 using {control down, option down, command down} -- ⌃⌥⌘↑ 全屏
end tell
✅ 优点:无需获取窗口对象,不依赖应用是否支持 AppleScript;适用于 Safari、Notes、Preview 等绝大多数原生及主流应用。
⚠️ 注意:需确保目标应用处于前台(已激活),否则快捷键作用于当前焦点窗口。
通过 bounds 设置“伪最大化”(精确控制,需计算安全区域)
适用于需要避开菜单栏/Dock 的场景,例如将窗口铺满主屏可用区域:
tell application "System Events"
set mainScreen to first screen
set {x, y, w, h} to bounds of mainScreen -- 返回 {0, 0, 宽, 高},已排除 Dock 和菜单栏
set frontApp to first application process whose frontmost is true
set frontWindow to first window of frontApp
set position of frontWindow to {x, y}
set size of frontWindow to {w, h}
end tell
✅ 优点:完全可控,适配多显示器(改用
second screen即可);适合固定布局自动化。
⚠️ 注意:对最小化或全屏中的窗口无效,需先还原——可在设置前加判断:if value of attribute "AXMinimized" of frontWindow then set value of attribute "AXMinimized" of frontWindow to false end if if value of attribute "AXFullScreen" of frontWindow then perform action "AXZoom" of frontWindow end if
封装为一键全屏启动函数(实用组合)
以下脚本启动 Safari 并立即全屏,延迟合理、含错误防护:
try
tell application "Safari" to activate
delay 0.3
tell application "System Events"
key code 126 using {control down, option down, command down}
end tell
on error errMsg
display alert "全屏失败:" & errMsg
end try
✅ 适用场景:绑定到快捷指令、程序坞图标或 Automator 快速操作,实现真正“一键全屏启动”。
不复杂但容易忽略权限和状态校验,实际效果取决于是否让窗口处于可操作状态。











