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

利用windows API函数 GetLastInputInfo()来判断系统空闲

//添加引用 using System.Runtime.InteropServices;

 1   // 创建结构体用于返回捕获时间
 2   [StructLayout(LayoutKind.Sequential)]
 3   struct LASTINPUTINFO
 4   {
 5   // 设置结构体块容量
 6   [MarshalAs(UnmanagedType.U4)]
 7   public int cbSize;
 8   // 捕获的时间
 9   [MarshalAs(UnmanagedType.U4)]
10   public uint dwTime;
11   }
12   [DllImport("user32.dll")]
13   private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
14 // 获取键盘和鼠标没有操作的时间
15   private static long GetLastInputTime() 
16   {
17   LASTINPUTINFO vLastInputInfo = new LASTINPUTINFO();
18   vLastInputInfo.cbSize = Marshal.SizeOf(vLastInputInfo);
19   // 捕获时间
20   if (!GetLastInputInfo(ref vLastInputInfo))
21        return 0;
22   else
23      return Environment.TickCount - (long)vLastInputInfo.dwTime;
24   } 

 

posted @ 2014-12-19 13:24  SpeakHero  阅读(2706)  评论(1编辑  收藏  举报