我希望在用户离开或回到计算机时启动一个脚本。在AppleScript中,是否有任何内置方法可以检查用户的状态?如果没有,我还能在OS X中使用什么呢?
我希望在用户离开或回到计算机时启动一个脚本。在AppleScript中,是否有任何内置方法可以检查用户的状态?如果没有,我还能在OS X中使用什么呢?
这里有一个可能适合你的命令。它会告诉你自鼠标移动或按键操作以来经过了多长时间。
set idleTime to do shell script "ioreg -c IOHIDSystem | awk '/HIDIdleTime/ {print $NF/1000000000; exit}'"
如果没有按键或鼠标移动一段时间,你可能会认为用户没有在使用计算机。通过巧妙地跟踪idleTime,您可以知道用户何时离开计算机以及何时返回。就像这样。
将此保存为AppleScript应用程序,并选中“运行处理程序后保持打开”复选框。您可以通过右键单击Dock图标并选择退出来随时退出它。
global timeBeforeComputerIsNotInUse, computerIsInUse, previousIdleTime
on run
set timeBeforeComputerIsNotInUse to 300 -- 5 minutes
set computerIsInUse to true
set previousIdleTime to 0
end run
on idle
set idleTime to (do shell script "ioreg -c IOHIDSystem | awk '/HIDIdleTime/ {print $NF/1000000000; exit}'") as number
if not computerIsInUse then
if idleTime is less than previousIdleTime then
set computerIsInUse to true
say "User is using the computer again."
end if
else if idleTime is greater than or equal to timeBeforeComputerIsNotInUse then
set computerIsInUse to false
say "User has left the computer."
end if
set previousIdleTime to idleTime
return 1
end idle