---
title: "鼠标闲置一段时间后自动隐藏"
author: "csstome"
date: "2008-12-15T12:38:00Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2008-12-15T12:38:00Z"
id: 1033057
url: "https://csstome.iteye.com/blog/1033057"
---

该问题来自论坛提问，两个api函数  
GetLastInputInfo：获取闲置时间  
ShowCursor：设置鼠标状态，这里要注意，本函数并不能直接影响鼠标状态，而是设置状态计数器，参数为True时计数器+1，反之-1，只有当计数器大于等于0时鼠标为显示，小于0时鼠标隐藏。所以可能会发生某次调用该函数而没有生效的情况。为了避免这个问题，可以用wile循环判断结果。

01. using System;
02. using System.Windows.Forms;
03. using System.Runtime.InteropServices;
04. namespace WindowsApplication5
05. {
06. public partial class Form1:Form
07. {
08. ///&lt;summary&gt;
09. ///获取鼠标闲置时间
10. ///&lt;/summary&gt;
11. \[StructLayout(LayoutKind.Sequential)]
12. public struct LASTINPUTINFO
13. {
14. \[MarshalAs(UnmanagedType.U4)]
15. public int cbSize;
16. \[MarshalAs(UnmanagedType.U4)]
17. public uint dwTime;
18. }
19. ///&lt;summary&gt;
20. ///获取鼠标闲置时间
21. ///&lt;/summary&gt;
22. ///&lt;paramname="plii"&gt;&lt;/param&gt;
23. ///&lt;returns&gt;&lt;/returns&gt;
24. \[DllImport( "user32.dll" )]
25. public static extern bool GetLastInputInfo( ref LASTINPUTINFOplii);
26. ///&lt;summary&gt;
27. ///设置鼠标状态的计数器（非状态）
28. ///&lt;/summary&gt;
29. ///&lt;paramname="bShow"&gt;状态&lt;/param&gt;
30. ///&lt;returns&gt;状态技术&lt;/returns&gt;
31. \[DllImport( "user32.dll" ,EntryPoint= "ShowCursor" ,CharSet=CharSet.Auto)]
32. public static extern int ShowCursor( bool bShow);
33. public Form1()
34. {
35. InitializeComponent();
36. //定时期
37. System.Windows.Forms.Timertimer= new Timer();
38. timer.Enabled= true ;
39. timer.Interval=100;
40. timer.Tick+= new EventHandler(timer\_Tick);
41. }
42. //鼠标状态计数器
43. int iCount=0;
44. void timer\_Tick( object sender,EventArgse)
45. {
46. //鼠标状态计数器&gt;=0的情况下鼠标可见，&lt;0不可见，并不是直接受api函数影响而改变
47. long i=getIdleTick();
48. if (i&gt;5000)
49. {
50. while (iCount&gt;=0)
51. {
52. iCount=ShowCursor( false );
53. }
54. }
55. else
56. {
57. while (iCount&lt;0)
58. {
59. iCount=ShowCursor( true );
60. }
61. }
62. }
63. ///&lt;summary&gt;
64. ///获取闲置时间
65. ///&lt;/summary&gt;
66. ///&lt;returns&gt;&lt;/returns&gt;
67. public long getIdleTick()
68. {
69. LASTINPUTINFOvLastInputInfo= new LASTINPUTINFO();
70. vLastInputInfo.cbSize=Marshal.SizeOf(vLastInputInfo);
71. if (!GetLastInputInfo( ref vLastInputInfo)) return 0;
72. return Environment.TickCount-( long )vLastInputInfo.dwTime;
73. }
74. }
75. }