2009-05-26 139 views
16

如何使用Python檢測系統是否在Windows上空閒(即沒有鍵盤或鼠標活動)。 這已被要求before,但pywin32模塊中似乎沒有GetLastInputInfo使用python檢測空閒時間

import ctypes 
GetLastInputInfo = ctypes.windll.User32.GetLastInputInfo # callable function pointer 

這可能不是你想要什麼,雖然,因爲它沒有提供在整個系統空閒信息,但只有約那個叫會話:

+5

由於這是之前問,你爲什麼又要求?你認爲什麼改變會產生不同的答案? – 2009-05-26 17:41:24

+1

也許現在有人可以回答這個問題,但這個老問題埋在了年代和默默無聞之中。你怎麼能「碰撞」別人的舊問題? – 2009-05-27 02:42:38

回答

18
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 

致電get_idle_duration()以秒爲單位獲得空閒時間。

6

好像GetLastInputInfo現在是在pywin32可供選擇:

win32api.GetLastInputInfo() 

的伎倆,並返回上一次用戶輸入動作的計時器滴答。

在這裏用一個例子程序

import time 
import win32api 
for i in range(10): 
    print(win32api.GetLastInputInfo()) 
    time.sleep(1) 

如果一個按下鍵/移動鼠標而腳本睡,印刷數量的變化。

1

@FogleBird的答案非常酷,而且工作很快,但我不知道它是如何工作的,所以這裏有一個測試示例。線程正在啓​​動,每10秒尋找最後一次空閒時間。如果在此時間窗口內進行任何移動,它將被打印出來。

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() 
3
import win32api 
def getIdleTime(): 
    return (win32api.GetTickCount() - win32api.GetLastInputInfo())/1000.0