c# 如何获取键盘和鼠标处于空闲状态的时间 ,可以通过windows api 函数GetLastInputInfo 或者 全局钩子HOOK来实现。
下面就针对GetLastInputInfo 写了个DEMO,判断鼠标键盘空闲时间超过15分站则自动弹出视频播放窗口播放视频。
新建windows 应用程序项目,代码如下:
01.using System;
02.using System.Collections.Generic;
03.using System.Windows.Forms;
04.using System.Runtime.InteropServices;
05.namespace APPDEMO
06.{
07. static class Program
08. {
09. private static VedioForm vf = null;
10. private static System.Windows.Forms.Timer timer1 = null;
11. /// <summary>
12. /// 应用程序的主入口点。
13. /// </summary>
14. [STAThread]
15. static void Main()
16. {
17. Application.EnableVisualStyles();
18. Application.SetCompatibleTextRenderingDefault(false);
19. //启用定时器
20. if (timer1 == null)
21. {
22. timer1 = new Timer();
23. }
24. timer1.Interval = 60*1000;
25. timer1.Tick += new EventHandler(timer1_Tick);
26. timer1.Start();
27. Application.Run(new MainForm());
28. }
29.private static void timer1_Tick(object sender, EventArgs e)
30. {
31. //判断空闲时间是否超过15分钟,超过则自动弹出视频播放窗口
32. if (GetIdleTick() / 1000 >= 15*60)
33. {
34. ShowVidioForm();
35. }
36. }
37. /// <summary>
38. /// 打开视频播放窗口
39. /// </summary>
40. private static void ShowVidioForm()
41. {
42. try
43. {
44. if (vf == null)
45. {
46. vf = new VedioForm();
47. }
48. vf.ShowDialog();
49. }
50. catch
51. {
52. }
53. }
54./// <summary>
55. /// 获取鼠标键盘空闲时间
56. /// </summary>
57. /// <returns></returns>
58. public static long GetIdleTick()
59. {
60. LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
61. lastInputInfo.cbSize = Marshal.SizeOf(lastInputInfo);
62. if (!GetLastInputInfo(ref lastInputInfo)) return 0;
63. return Environment.TickCount - (long)lastInputInfo.dwTime;
64. }
65. [StructLayout(LayoutKind.Sequential)]
66. private struct LASTINPUTINFO
67. {
68. [MarshalAs(UnmanagedType.U4)]
69. public int cbSize;
70. [MarshalAs(UnmanagedType.U4)]
71. public uint dwTime;
72. }
73. /// <summary>
74. /// 调用windows API获取鼠标键盘空闲时间
75. /// </summary>
76. /// <param name="plii"></param>
77. /// <returns></returns>
78. [DllImport("user32.dll")]
79. private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
80. }
81.}