延时相关
解决延时问题,可写一个延时方法:
public static void Delay(int milliSecond)//延时函数 { int start = Environment.TickCount; while (Math.Abs(Environment.TickCount - start) < milliSecond)//毫秒 { Application.DoEvents();//可执行某无聊的操作 } }
如果需要实时监控,比如软件无操作多少时间后,执行某一操作,可使用timer实时监控,判断键盘无操作开始计时,到指定时间后即触发timer事件。
#region 判断鼠标键盘空闲 ////// 获取鼠标键盘空闲时间 /// /// public static long GetIdleTick() { LASTINPUTINFO lastInputInfo = new LASTINPUTINFO(); lastInputInfo.cbSize = Marshal.SizeOf(lastInputInfo); if (!GetLastInputInfo(ref lastInputInfo)) return 0; return Environment.TickCount - (long)lastInputInfo.dwTime; } [StructLayout(LayoutKind.Sequential)] private struct LASTINPUTINFO { [MarshalAs(UnmanagedType.U4)] public int cbSize; [MarshalAs(UnmanagedType.U4)] public uint dwTime; } /// /// 调用windows API获取鼠标键盘空闲时间 /// /// /// [DllImport("user32.dll")] private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); #endregion
可根据鼠标键盘空闲时间进行判断,写在timer1_Tick事件里面,根据获取的时间进行判断。
private void timer1_Tick_1(object sender, EventArgs e) { if (GetIdleTick() / 1000 >= 10)//10为秒数,timer事件频率要设为1000ms { //执行的代码 } }