Skip to content

Instantly share code, notes, and snippets.

@KingYes
Created October 7, 2014 04:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save KingYes/da8b0f1b9f290d7378f4 to your computer and use it in GitHub Desktop.
Save KingYes/da8b0f1b9f290d7378f4 to your computer and use it in GitHub Desktop.
Sample code in Python to detect idle time
import sys
if sys.platform == 'win32':
from ctypes import *
class LASTINPUTINFO(Structure):
_fields_ = [
('cbSize', c_uint),
('dwTime', c_int),
]
def get_idle_duration():
lastInputInfo = LASTINPUTINFO()
lastInputInfo.cbSize = sizeof(lastInputInfo)
if windll.user32.GetLastInputInfo(byref(lastInputInfo)):
millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime
return millis / 1000.0
else:
return 0
else:
def get_idle_duration():
return 0
if __name__ == '__main__':
import time
while True:
duration = get_idle_duration()
print 'User idle for %.2f seconds.' % duration
time.sleep(1)
@michaeldrouin
Copy link

so if the system is not windows, it will always return saying the idle time is 0, even if it isn't?

@jaymewoodbridge
Copy link

jaymewoodbridge commented Feb 27, 2020

Just applied to my script in Python 3.7
If people are curious here is my code for 3.7+ users

'if sys.platform == 'win32':
    from ctypes import Structure, windll, c_uint, c_int, sizeof, byref
    
    class LASTINPUTINFO(Structure):
        _fields_ = [
            ('cbSize', c_uint),
            ('dwTime', c_int),
        ]
        
    def get_idle_duration():
        lastInputInfo = LASTINPUTINFO()
        lastInputInfo.cbSize = sizeof(lastInputInfo)
        if windll.user32.GetLastInputInfo(byref(lastInputInfo)):
            millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime
            return millis / 1000.0
        else:
            return 0
else:
    def get_idle_duration():
        return 0
        
if __name__ == '__main__':
    import time
    while True:
        duration = str(get_idle_duration())
        print('User idle for seconds.' + duration)
        time.sleep(1)`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment