using ProjectBase.Data.Redis; using ProjectBase.Util; using System; using System.Runtime.InteropServices; namespace SIMDP.Project { public class UserIdleStatusHelper { //: System.ComponentModel.Component private bool isIdle = false; private int idleTimeOut = 5000;//获取一次忙碌状态后,最少维持的时长 private int resolution = 100; private int lastActivity = Environment.TickCount; private System.Timers.Timer timer = new System.Timers.Timer(); public event EventHandler OnIdle; public event EventHandler OnActive; RedisHelper redis = new RedisHelper(); public UserIdleStatusHelper(int miliseconds) { this.idleTimeOut = miliseconds; } public void Start() { this.isIdle = false; timer.Elapsed -= Timer_Elapsed; timer.Elapsed += Timer_Elapsed; timer.Interval = this.resolution; timer.Start(); } public void Stop() { timer.Stop(); } public bool IsIdle { get { return this.isIdle; } private set { if (this.isIdle != value) { this.isIdle = value; if (isIdle && OnIdle != null) { OnIdle(this, EventArgs.Empty); } if (!isIdle && OnActive != null) { OnActive(this, EventArgs.Empty); } } } } public int IdleTimeOut { get { return idleTimeOut; } set { idleTimeOut = Math.Max(50, value); } } public int Resolution { get { return resolution; } set { resolution = Math.Max(50, value); } } private void Timer_Elapsed(object sender, EventArgs e) { LASTINPUTINFO lastInputInfo = new LASTINPUTINFO(); lastInputInfo.size = 8; if (GetLastInputInfo(ref lastInputInfo)) { lastActivity = Math.Max(lastActivity, lastInputInfo.lastTick); int diff = Environment.TickCount - lastActivity; if (this.IsIdle != diff > this.IdleTimeOut) { this.IsIdle = diff > this.IdleTimeOut; //call UI change if (redis == null) redis = new RedisHelper(); redis.Publish(SysEnvironment.UserOperateState, ""); } } } [StructLayout(LayoutKind.Sequential)] private struct LASTINPUTINFO { public int size; public int lastTick; } [DllImport("User32")] private static extern bool GetLastInputInfo(ref LASTINPUTINFO lii); } }