鼠标闲置一段时间后自动隐藏
该问题来自论坛提问,两个api函数
GetLastInputInfo:获取闲置时间
ShowCursor:设置鼠标状态,这里要注意,本函数并不能直接影响鼠标状态,而是设置状态计数器,参数为True时计数器+1,反之-1,只有当计数器大于等于0时鼠标为显示,小于0时鼠标隐藏。所以可能会发生某次调用该函数而没有生效的情况。为了避免这个问题,可以用wile循环判断结果。
- using System;
- using System.Windows.Forms;
- using System.Runtime.InteropServices;
- namespace WindowsApplication5
- {
- public partial class Form1:Form
- {
- ///<summary>
- ///获取鼠标闲置时间
- ///</summary>
- [StructLayout(LayoutKind.Sequential)]
- public struct LASTINPUTINFO
- {
- [MarshalAs(UnmanagedType.U4)]
- public int cbSize;
- [MarshalAs(UnmanagedType.U4)]
- public uint dwTime;
- }
- ///<summary>
- ///获取鼠标闲置时间
- ///</summary>
- ///<paramname="plii"></param>
- ///<returns></returns>
- [DllImport( "user32.dll" )]
- public static extern bool GetLastInputInfo( ref LASTINPUTINFOplii);
- ///<summary>
- ///设置鼠标状态的计数器(非状态)
- ///</summary>
- ///<paramname="bShow">状态</param>
- ///<returns>状态技术</returns>
- [DllImport( "user32.dll" ,EntryPoint= "ShowCursor" ,CharSet=CharSet.Auto)]
- public static extern int ShowCursor( bool bShow);
- public Form1()
- {
- InitializeComponent();
- //定时期
- System.Windows.Forms.Timertimer= new Timer();
- timer.Enabled= true ;
- timer.Interval=100;
- timer.Tick+= new EventHandler(timer_Tick);
- }
- //鼠标状态计数器
- int iCount=0;
- void timer_Tick( object sender,EventArgse)
- {
- //鼠标状态计数器>=0的情况下鼠标可见,<0不可见,并不是直接受api函数影响而改变
- long i=getIdleTick();
- if (i>5000)
- {
- while (iCount>=0)
- {
- iCount=ShowCursor( false );
- }
- }
- else
- {
- while (iCount<0)
- {
- iCount=ShowCursor( true );
- }
- }
- }
- ///<summary>
- ///获取闲置时间
- ///</summary>
- ///<returns></returns>
- public long getIdleTick()
- {
- LASTINPUTINFOvLastInputInfo= new LASTINPUTINFO();
- vLastInputInfo.cbSize=Marshal.SizeOf(vLastInputInfo);
- if (!GetLastInputInfo( ref vLastInputInfo)) return 0;
- return Environment.TickCount-( long )vLastInputInfo.dwTime;
- }
- }
- }