AppleScript设置闲置15分钟关显示器报错求助
修复方案
1. 语法错误修复及逻辑优化
原脚本的语法错误出在set currentPosition to get the mouse location这一行,AppleScript中获取鼠标位置无需get和the修饰,同时嵌套的tell application "System Events"会导致上下文冲突,以下是修复并优化逻辑后的脚本:
set frontApp to name of first application process whose frontmost is true set mouseMoved to false set idleMinutes to 0 repeat tell application "System Events" set currentPosition to mouse location end tell if currentPosition is not equal to {-1, -1} and currentPosition is not in {{0, 0}, {0, 1079}} then set mouseMoved to true end if if mouseMoved is false then set idleMinutes to idleMinutes + 1 if idleMinutes >= 15 then tell application "System Preferences" activate set current pane to pane "com.apple.preference.displays" end tell tell application "System Events" to tell process "System Preferences" click button "Display" of tab group 1 of window 1 delay 2 click radio button "Turn off after: 15 min" of tab group 1 of window 1 end tell tell application "System Preferences" to quit set idleMinutes to 0 end if else set idleMinutes to 0 set mouseMoved to false end if delay 60 end repeat
2. 更高效的替代实现
通过系统偏好设置操作界面易受语言、版本影响出错,推荐用pmset命令直接操作,更稳定可靠:
方式一:设置显示器自动关闭时间
set idleThreshold to 15 set lastMousePos to {-1, -1} set idleCount to 0 repeat tell application "System Events" set currentMousePos to mouse location end tell if currentMousePos is not equal to lastMousePos then set lastMousePos to currentMousePos set idleCount to 0 else set idleCount to idleCount + 1 if idleCount >= idleThreshold then do shell script "pmset displaysleep 15" set idleCount to 0 end if end if delay 60 end repeat
方式二:闲置15分钟后立即关闭显示器
set idleThreshold to 15 set lastMousePos to {-1, -1} set idleCount to 0 repeat tell application "System Events" set currentMousePos to mouse location end tell if currentMousePos ≠ lastMousePos then set lastMousePos to currentMousePos set idleCount to 0 else set idleCount to idleCount + 1 if idleCount ≥ idleThreshold then do shell script "pmset displaysleepnow" set idleCount to 0 end if end if delay 60 end repeat
错误原因说明
get the mouse location违反AppleScript语法规范,正确写法为直接调用mouse location属性;- 嵌套的
tell application "System Events"会造成上下文混乱,拆分后可避免此类问题; - 原脚本未实现累计闲置时间的逻辑,仅单次检查鼠标位置就执行操作,不符合“闲置15分钟”的需求。
内容的提问来源于stack exchange,提问作者Patryk Petryszen
相关产品推荐
相关产品推荐

