detecting idle time using python

后端 未结 5 1085
梦毁少年i
梦毁少年i 2020-12-24 07:28

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

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-24 08:04

    @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()
    

提交回复
热议问题