Mac下Bash/AppleScript无法调整已打开窗口大小求助
修复Mac Bash脚本的窗口分屏功能
你的脚本已经实现了新建桌面和打开应用的功能,窗口调整失效主要是因为屏幕尺寸获取、窗口定位和等待逻辑的问题,以下是修复后的完整脚本及说明:
修复后的完整脚本
#!/bin/bash app1="Zotero" app2="Google Chrome" app3="GoodNotes" app4="Finder" # 创建新桌面 osascript <<END tell application "System Events" do shell script quoted form of "/System/Applications/Mission Control.app/Contents/MacOS/Mission Control" delay 0.5 click button 1 of group "Spaces Bar" of group 1 of group "Mission Control" of process "Dock" delay 0.5 do shell script quoted form of "/System/Applications/Mission Control.app/Contents/MacOS/Mission Control" end tell END # 切换到新桌面 sleep 1 osascript -e 'tell application "System Events" to key code 124 using control down' # 打开应用 open -a "$app1" open -na "$app2" --args --new-window "https://example.com" open -a "$app3" open -a "$app4" ~/Desktop # 定义窗口调整函数 resize_and_position_app() { local app_name=$1 local x=$2 local y=$3 local width=$4 local height=$5 # 等待应用窗口加载完成 osascript <<END tell application "$app_name" activate repeat until exists window 1 delay 0.5 end repeat tell window 1 set bounds to {$x, $y, $x + $width, $y + $height} end tell end tell END } # 获取屏幕可用尺寸(自动适配菜单栏高度) screen_info=$(osascript -e 'tell application "Finder" to get bounds of window of desktop') screen_width=$(echo "$screen_info" | awk -F ', ' '{print $3}') screen_height=$(echo "$screen_info" | awk -F ', ' '{print $4}') menu_bar_height=22 # 大部分系统适用,若你的系统菜单栏高度不同可修改 # 计算四分屏尺寸 quarter_width=$((screen_width / 2)) quarter_height=$(((screen_height - menu_bar_height) / 2)) # 分别调整四个应用的窗口位置和大小 resize_and_position_app "$app1" 0 $menu_bar_height $quarter_width $quarter_height # 左上 resize_and_position_app "$app2" $quarter_width $menu_bar_height $quarter_width $quarter_height # 右上 resize_and_position_app "$app3" 0 $((menu_bar_height + quarter_height)) $quarter_width $quarter_height # 左下 resize_and_position_app "$app4" $quarter_width $((menu_bar_height + quarter_height)) $quarter_width $quarter_height # 右下
关键修复点说明
- 屏幕尺寸获取优化:通过Finder的桌面窗口边界获取准确的屏幕可用宽度和高度,避免
system_profiler的兼容性问题 - 窗口等待逻辑:新增循环检查,直到应用窗口存在再执行调整,替代固定sleep时间,适配不同应用的启动速度
- 应用定位方式改进:直接使用应用名称调用AppleScript操作窗口,避免PID多进程导致的定位错误,同时激活应用确保操作的是当前窗口
- 尺寸计算修正:计算高度时扣除菜单栏高度,确保窗口不会被菜单栏遮挡,同时用
bounds属性一次性设置位置和大小,比分开设置position和size更稳定
内容的提问来源于stack exchange,提问作者Mark Pampuch
相关产品推荐
相关产品推荐

