求助:AppleScript操作Sleep Control Center菜单栏图标遇两类问题
解决Sleep Control Center菜单栏图标的AppleScript控制问题
右键打开上下文菜单的正确写法
从Mojave开始,旧的右键模拟方法失效,直接用using {button 2}参数就能实现右键点击菜单栏图标,不用折腾ignoring application responses和killall System Events——后者会直接中断System Events进程,反而导致后续菜单操作失败。另外务必确保你的脚本工具(终端/脚本编辑器)已经在「系统设置-隐私与安全性-辅助功能」里获得权限。
代码示例:
tell application "System Events" to tell process "Sleep Control Center" click menu bar item 1 of menu bar 1 using {button 2} end tell
找不到「Deactivate」菜单项的原因及修复
你的代码里菜单层级嵌套错误,正确的层级是菜单栏项 -> 菜单,不需要重复引用menu bar item。另外打开菜单后必须加一点延迟,给系统留足加载菜单内容的时间,否则System Events还没识别到菜单项就会报错。
修正后的完整代码:
tell application "System Events" tell process "Sleep Control Center" -- 右键打开上下文菜单 click menu bar item 1 of menu bar 1 using {button 2} delay 0.2 -- 可根据自己系统的响应速度调整 -- 点击Deactivate菜单项 click menu item "Deactivate" of menu 1 of menu bar item 1 of menu bar 1 end tell end tell
如果还是报错,先检查菜单项的实际名称(有没有大小写错误、是否和界面显示完全一致),或者用get name of every menu item of menu 1 of menu bar item 1 of menu bar 1命令打印所有菜单项名称,确认目标项的准确名称。
内容的提问来源于stack exchange,提问作者daydr3amer
相关产品推荐
相关产品推荐

