思路:步骤1.使用API GetLastInputInfo 取出系统最近的输入时间
步骤2.使用系统启动后时间 System.Environment.TickCount 减去 系统最近的输入时间。
public partial class Form42 : Form
{
public Form42()
{
InitializeComponent();
}
//调用API GetLastInputInfo 返回最近的输入动作
[System.Runtime.InteropServices.DllImport("user32.dll")]
public extern static bool GetLastInputInfo(ref LASTINPUTINFO xLastInput);
private void timer1_Tick(object sender, EventArgs e)
{
//使用时钟,每1秒钟,取一次
LASTINPUTINFO vLastInputInfo = new LASTINPUTINFO();
vLastInputInfo.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(vLastInputInfo);
if (GetLastInputInfo(ref vLastInputInfo) == false)
return;
//System.Environment.TickCount ,指系统后的毫秒数
//vLastInputInfo.dwTime,指GetLastInputInfo取出值:指在系统启后的这一刻用户做了输入动作
if ((System.Environment.TickCount - vLastInputInfo.dwTime) > 2 * 1000)
{
//当系统闲置2秒后,即输出调试信息
System.Diagnostics.Debug.WriteLine("Debug1" + ((System.Environment.TickCount - vLastInputInfo.dwTime) / 1000).ToString());
}
}
}
//GetLastInputInfo 用到的参数结构体
public struct LASTINPUTINFO
{
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.U4)]
public int cbSize;
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.U4)]
public uint dwTime;
}