该问题来自论坛提问,两个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>
- /// <param name="plii"></param>
- /// <returns></returns>
- [DllImport( "user32.dll" )]
- public static extern bool GetLastInputInfo( ref LASTINPUTINFO plii);
- /// <summary>
- /// 设置鼠标状态的计数器(非状态)
- /// </summary>
- /// <param name="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.Timer timer = new Timer();
- timer.Enabled = true ;
- timer.Interval = 100;
- timer.Tick += new EventHandler(timer_Tick);
- }
- //鼠标状态计数器
- int iCount = 0;
- void timer_Tick( object sender, EventArgs e)
- {
- //鼠标状态计数器>=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()
- {
- LASTINPUTINFO vLastInputInfo = new LASTINPUTINFO();
- vLastInputInfo.cbSize = Marshal.SizeOf(vLastInputInfo);
- if (!GetLastInputInfo( ref vLastInputInfo)) return 0;
- return Environment.TickCount - ( long )vLastInputInfo.dwTime;
- }
- }
- }