UserIdleStatusHelper.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. using ProjectBase.Data.Redis;
  2. using ProjectBase.Util;
  3. using System;
  4. using System.Runtime.InteropServices;
  5. namespace SIMDP.Project
  6. {
  7. public class UserIdleStatusHelper
  8. {
  9. //: System.ComponentModel.Component
  10. private bool isIdle = false;
  11. private int idleTimeOut = 5000;//获取一次忙碌状态后,最少维持的时长
  12. private int resolution = 100;
  13. private int lastActivity = Environment.TickCount;
  14. private System.Timers.Timer timer = new System.Timers.Timer();
  15. public event EventHandler OnIdle;
  16. public event EventHandler OnActive;
  17. RedisHelper redis = new RedisHelper();
  18. public UserIdleStatusHelper(int miliseconds)
  19. {
  20. this.idleTimeOut = miliseconds;
  21. }
  22. public void Start()
  23. {
  24. this.isIdle = false;
  25. timer.Elapsed -= Timer_Elapsed;
  26. timer.Elapsed += Timer_Elapsed;
  27. timer.Interval = this.resolution;
  28. timer.Start();
  29. }
  30. public void Stop()
  31. {
  32. timer.Stop();
  33. }
  34. public bool IsIdle
  35. {
  36. get { return this.isIdle; }
  37. private set
  38. {
  39. if (this.isIdle != value)
  40. {
  41. this.isIdle = value;
  42. if (isIdle && OnIdle != null)
  43. {
  44. OnIdle(this, EventArgs.Empty);
  45. }
  46. if (!isIdle && OnActive != null)
  47. {
  48. OnActive(this, EventArgs.Empty);
  49. }
  50. }
  51. }
  52. }
  53. public int IdleTimeOut
  54. {
  55. get { return idleTimeOut; }
  56. set { idleTimeOut = Math.Max(50, value); }
  57. }
  58. public int Resolution
  59. {
  60. get { return resolution; }
  61. set { resolution = Math.Max(50, value); }
  62. }
  63. private void Timer_Elapsed(object sender, EventArgs e)
  64. {
  65. LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
  66. lastInputInfo.size = 8;
  67. if (GetLastInputInfo(ref lastInputInfo))
  68. {
  69. lastActivity = Math.Max(lastActivity, lastInputInfo.lastTick);
  70. int diff = Environment.TickCount - lastActivity;
  71. if (this.IsIdle != diff > this.IdleTimeOut)
  72. {
  73. this.IsIdle = diff > this.IdleTimeOut;
  74. //call UI change
  75. if (redis == null) redis = new RedisHelper();
  76. redis.Publish(SysEnvironment.UserOperateState, "");
  77. }
  78. }
  79. }
  80. [StructLayout(LayoutKind.Sequential)]
  81. private struct LASTINPUTINFO
  82. {
  83. public int size;
  84. public int lastTick;
  85. }
  86. [DllImport("User32")]
  87. private static extern bool GetLastInputInfo(ref LASTINPUTINFO lii);
  88. }
  89. }