且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-01 20:13:58

这是一个可能对您有用的命令.这将告诉您自移动鼠标或按下按键以来已经过去了多长时间.

Here's a command that might work for you. This will tell you how long it's been since the mouse moved or a keystroke was pressed.

set idleTime to do shell script "ioreg -c IOHIDSystem | awk '/HIDIdleTime/ {print $NF/1000000000; exit}'"

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

So you might assume that if no key was pressed or the mouse was moved for a period of time then the user is not using the computer. With some clever tracking of the idleTime you can tell when the user left the computer and also when he returned. Something like this.

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

Save this as an applescript application and check the "stay open after run handler" checkbox. You can quit it any time by right-clicking on the dock icon and choosing quit.

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