如何在OS X中检测用户是否离开?

9

我希望在用户离开或回到计算机时启动一个脚本。在AppleScript中,是否有任何内置方法可以检查用户的状态?如果没有,我还能在OS X中使用什么呢?

2个回答

18

这里有一个可能适合你的命令。它会告诉你自鼠标移动或按键操作以来经过了多长时间。

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

这几乎是我想要的,但是当我观看视频/YouTube时,它能否正常工作(因为这不应被视为闲置)? - Richard Fu
1
@RichardFu 请尝试使用 "pmset -g" 命令,例如 https://dev59.com/nHnZa4cB1Zd3GeqPoEd6 - Andy K

3
请查看iAway,这是一个小型应用程序,它允许您在离开 Mac 时运行 Apple Script 并返回。我使用它来设置我的即时通讯应用程序的在线状态,并在离开时启动屏幕保护程序,以及在返回时将我的在线状态设置回来。该应用程序配备了其他很酷的功能,实际上可以利用计算机视觉检测您是否身体离开。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接