鼠标闲置一段时间后自动隐藏


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

  1. using System;
  2. using System.Windows.Forms;
  3. using System.Runtime.InteropServices;
  4. namespace WindowsApplication5
  5. {
  6. public partial class Form1:Form
  7. {
  8. ///<summary>
  9. ///获取鼠标闲置时间
  10. ///</summary>
  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. ///<summary>
  20. ///获取鼠标闲置时间
  21. ///</summary>
  22. ///<paramname="plii"></param>
  23. ///<returns></returns>
  24. [DllImport( "user32.dll" )]
  25. public static extern bool GetLastInputInfo( ref LASTINPUTINFOplii);
  26. ///<summary>
  27. ///设置鼠标状态的计数器(非状态)
  28. ///</summary>
  29. ///<paramname="bShow">状态</param>
  30. ///<returns>状态技术</returns>
  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. //鼠标状态计数器>=0的情况下鼠标可见,<0不可见,并不是直接受api函数影响而改变
  47. long i=getIdleTick();
  48. if (i>5000)
  49. {
  50. while (iCount>=0)
  51. {
  52. iCount=ShowCursor( false );
  53. }
  54. }
  55. else
  56. {
  57. while (iCount<0)
  58. {
  59. iCount=ShowCursor( true );
  60. }
  61. }
  62. }
  63. ///<summary>
  64. ///获取闲置时间
  65. ///</summary>
  66. ///<returns></returns>
  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. }



优质内容筛选与推荐>>
1、转 美制电线标准AWG与公制、英制单位对照
2、Keil中的警告的解决
3、asp.net HttpHand和HttpModule的详细解释,包括Asp.Net对Http请求的处理流程。
4、php-fpm-运行原理(转)
5、职业理想


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号