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

Bob*_*lev 5 macos applescript

我想在用户离开或返回计算机时启动脚本.AppleScript中是否有任何内置方法来检查用户的状态?如果不是我可以在OS X中使用什么?

reg*_*633 11

这是一个可能适合您的命令.这将告诉您自鼠标移动或按下击键后多长时间.

set idleTime to do shell script "ioreg -c IOHIDSystem | awk '/HIDIdleTime/ {print $NF/1000000000; exit}'"
Run Code Online (Sandbox Code Playgroud)

因此,您可能会认为如果未按任何键或鼠标移动一段时间,则用户不使用计算机.通过对idleTime的一些巧妙跟踪,您可以判断用户何时离开计算机以及何时返回.像这样的东西.

将其保存为applescript应用程序并选中"在运行处理程序后保持打开状态"复选框.您可以随时通过右键单击停靠栏图标并选择退出来退出.

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
Run Code Online (Sandbox Code Playgroud)