1.利用windows API函数 GetLastInputInfo()来判断系统空闲
//类内添加引用 using System.Runtime.InteropServices;
// 创建结构体用于返回捕获时间
[StructLayout(LayoutKind.Sequential)]
struct LASTINPUTINFO
{
// 设置结构体块容量
[MarshalAs(UnmanagedType.U4)]
public int cbSize;
// 捕获的时间
[MarshalAs(UnmanagedType.U4)]
public uint dwTime;
}
[DllImport("user32.dll")]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
获取键盘和鼠标没有操作的时间
private static long GetLastInputTime()
{
LASTINPUTINFO vLastInputInfo = new LASTINPUTINFO();
vLastInputInfo.cbSize = Marshal.SizeOf(vLastInputInfo);
// 捕获系统空闲时间(键盘及鼠标未操作时间)
if (!GetLastInputInfo(ref vLastInputInfo))
return 0;
else
return Environment.TickCount - (long)vLastInputInfo.dwTime;//单位ms
}