How to detect if user is away in OS X?

前端 未结 2 1323
别那么骄傲
别那么骄傲 2021-01-05 03:56

I want to start a script when user goes away or returns back to computer. Is there any built-in method in AppleScript to check user\'s state? If not what else can I use in O

2条回答
  •  日久生厌
    2021-01-05 04:33

    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}'"
    

    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.

    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
    

提交回复
热议问题