How do I detect if the system is idle on Windows using Python (i.e. no keyboard or mouse activity).
This has already been asked before, but there doesn\'t seem to be a
import win32api
def getIdleTime():
return (win32api.GetTickCount() - win32api.GetLastInputInfo()) / 1000.0
from ctypes import Structure, windll, c_uint, sizeof, byref
class LASTINPUTINFO(Structure):
_fields_ = [
('cbSize', c_uint),
('dwTime', c_uint),
]
def get_idle_duration():
lastInputInfo = LASTINPUTINFO()
lastInputInfo.cbSize = sizeof(lastInputInfo)
windll.user32.GetLastInputInfo(byref(lastInputInfo))
millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime
return millis / 1000.0
Call get_idle_duration()
to get idle time in seconds.
Seems like GetLastInputInfo
is now available in pywin32:
win32api.GetLastInputInfo()
does the trick and returns the timer tick from the last user input action.
Here with an example program
import time
import win32api
for i in range(10):
print(win32api.GetLastInputInfo())
time.sleep(1)
If one presses a key/moves the mouse while the script sleeps, the printed number changes.
@FogleBird's answer is pretty cool and working, but in a hurry i wasn't sure how it works, so a little test example here. A thread is starting, looking for last idle time every 10 seconds. If any movement is made within this time window, it will be printed out.
from ctypes import Structure, windll, c_uint, sizeof, byref
import threading
//Print out every n seconds the idle time, when moving mouse, this should be < 10
def printit():
threading.Timer(10.0, printit).start()
print get_idle_duration()
class LASTINPUTINFO(Structure):
_fields_ = [
('cbSize', c_uint),
('dwTime', c_uint),
]
def get_idle_duration():
lastInputInfo = LASTINPUTINFO()
lastInputInfo.cbSize = sizeof(lastInputInfo)
windll.user32.GetLastInputInfo(byref(lastInputInfo))
millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime
return millis / 1000.0
printit()
Actually, you can access GetLastInputInfo
via the cytpes
library:
import ctypes
GetLastInputInfo = ctypes.windll.User32.GetLastInputInfo # callable function pointer
This might not be what you want though, as it does not provide idle information across the whole system, but only about the session that called the function. See MSDN docs.
Alternatively, you could check if the system is locked, or if the screen-saver has been started.