macOS无原生自动投屏API,但可通过AppleScript结合system_profiler、defaults和displayplacer实现半自动镜像切换、主屏设定、USB触发检测及一键还原;需配合launchd轮询或热键调用,适用于Ventura及以上系统。
macos 本身不提供直接的“自动投屏”系统级 api,但可通过 applescript 结合系统偏好设置、显示器管理命令和触发机制(如连接外接显示器时)实现半自动化的投屏配置。以下方案聚焦实用、稳定、无需第三方工具,适用于 macos ventura 及更新版本(含 sonoma)。
一、检测并切换到镜像模式(最常用场景)
当外接显示器接入后,脚本可自动将显示模式从“扩展”切为“镜像”,适合会议/演示前快速准备。
- AppleScript 无法直接读取当前显示模式,但可通过
system_profiler SPDisplaysDataType判断是否连接多显示器 - 使用
defaults write修改镜像开关(需配合重启窗口服务器) - 关键命令组合:
do shell script "defaults -currentHost write NSGlobalDomain AppleDisplayMirroringEnabled -bool true" do shell script "killall -HUP WindowServer"
⚠️ 注意:此操作会短暂闪屏,且仅在系统设置中已启用“镜像显示器”选项时生效(需提前勾选一次)。
二、按显示器名称自动排列并设为主屏
若固定使用某台外接显示器(如“Dell U2723DX”),可脚本化设定其为主显示器并调整位置。
- 先用
system_profiler SPDisplaysDataType | grep 'Resolution\|Resolution:'或displayplacer list(需安装 displayplacer)获取设备 ID 或名称 - 推荐使用开源工具 displayplacer(轻量、无后台进程),通过 AppleScript 调用:
do shell script "displayplacer 'id:81926500-0000-0000-0000-000000000000 res:1920x1080 hz:60 color_depth:8 scaling:on origin:(0,0) degree:0' 'id:81926501-0000-0000-0000-000000000000 res:1920x1080 hz:60 color_depth:8 scaling:on origin:(1920,0) degree:0'"
? 提示:运行 displayplacer list 一次,复制对应显示器的完整 id 和参数,保存为变量或配置文件,便于复用。
使用 inotes CLI 从终端管理 Apple Notes。当需要在 macOS 的 Notes.app 中列出、读取、创建、编辑、删除或搜索备忘录时使用。
三、结合 USB 设备接入触发自动执行
真正“自动”的关键在于事件监听。macOS 原生不支持显示器热插拔 AppleScript 事件,但可用以下替代方式:
-
Folder Action + I/O Kit 日志监控:监听
/var/log/system.log中 “Display” 或 “IOFramebuffer” 相关条目(需 sudo 权限,较重) - 更轻量推荐:用 launchd 定期检查显示器数量(每 5 秒)
- 创建 plist 放入
~/Library/LaunchAgents/,调用一个 Shell 脚本,该脚本内嵌 AppleScript:
#!/bin/bash count=$(system_profiler SPDisplaysDataType | grep -c "Resolution:") if [ "$count" -gt "1" ]; then osascript -e 'do shell script "displayplacer ..."' 2>/dev/null fi
四、一键恢复笔记本屏为主屏(退出投屏)
会议结束拔掉线缆后,常需还原为仅内置屏工作。可绑定快捷键(如 Cmd+Opt+P)执行:
- 关闭镜像:
defaults -currentHost write NSGlobalDomain AppleDisplayMirroringEnabled -bool false - 禁用外接屏(设分辨率 0×0)或移至负坐标隐藏
- 最稳妥方式:用 displayplacer 恢复预存的“仅内置屏”布局
do shell script "displayplacer 'id:... res:1680x1050 ... origin:(0,0)'" do shell script "killall -HUP WindowServer"
✅ 建议将“投屏配置”和“还原配置”分别存为两个 .scpt 文件,再用 Alfred / FastScripts 绑定热键,体验接近一键切换。

















