如何使用Python检测系统是否在Windows上空闲(即没有键盘或鼠标活动).这已经被问之前,但似乎没有成为GetLastInputInfo
中pywin32
模块.
Fog*_*ird 23
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
Run Code Online (Sandbox Code Playgroud)
呼叫get_idle_duration()
以秒为单位获得空闲时间.
好像GetLastInputInfo
现在可以在pywin32中找到:
win32api.GetLastInputInfo()
Run Code Online (Sandbox Code Playgroud)
诀窍并返回上次用户输入操作的计时器滴答.
这里有一个示例程序
import time
import win32api
for i in range(10):
print(win32api.GetLastInputInfo())
time.sleep(1)
Run Code Online (Sandbox Code Playgroud)
如果在脚本休眠时按下一个键/移动鼠标,则打印的数字会发生变化.
import win32api
def getIdleTime():
return (win32api.GetTickCount() - win32api.GetLastInputInfo()) / 1000.0
Run Code Online (Sandbox Code Playgroud)
GetLastInputInfo
实际上,您可以通过库访问cytpes
:
import ctypes
GetLastInputInfo = ctypes.windll.User32.GetLastInputInfo # callable function pointer
Run Code Online (Sandbox Code Playgroud)
但这可能不是您想要的,因为它不提供整个系统的空闲信息,而仅提供有关调用该函数的会话的信息。 请参阅 MSDN 文档。
或者,您可以检查系统是否已锁定,或者屏幕保护程序是否已启动。