C# 判断系统空闲(键盘、鼠标不操作一段时间)

转载自:https://www.cnblogs.com/speakhero/p/4173703.html

利用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;
}

你可能感兴趣的:(C# 判断系统空闲(键盘、鼠标不操作一段时间))