看到优酷客户端有这么个功能,也想自己来实现一下,真正动手写,发现效果不理想,stackoverflow上搜到 http://stackoverflow.com/questions/744980/hide-mouse-cursor-after-an-idle-time,代码如下:
public partial class Form1 : Form { public TimeSpan TimeoutToHide { get; private set; } public DateTime LastMouseMove { get; private set; } public bool IsHidden { get; private set; } public Form1() { InitializeComponent(); TimeoutToHide = TimeSpan.FromSeconds(5); this.MouseMove += new MouseEventHandler(Form1_MouseMove); } void Form1_MouseMove(object sender, MouseEventArgs e) { LastMouseMove = DateTime.Now; if (IsHidden) { Cursor.Show(); IsHidden = false; } } private void timer1_Tick(object sender, EventArgs e) { TimeSpan elaped = DateTime.Now - LastMouseMove; if (elaped >= TimeoutToHide && !IsHidden) { Cursor.Hide(); IsHidden = true; } } }
试了下,效果也不佳。在此寻求一个比较好的办法!
使用Form.Idle事件捕获空闲。
这个应该是Application的事件吧
@jello chen: 呵呵,忘记了,应该是APPLICATION的,只是记得有这个事件用来跟踪CPU空闲状态的。
@519740105: 其实这里空闲的意思只是当一段时间没有鼠标动作时鼠标就隐藏
@jello chen: 我明白你的意思了。
下面的代码,对你应该有帮助的:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Diagnostics; using System.Runtime.InteropServices; namespace WindowsFormsApplication1 { 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; } } }
@519740105: 非常感谢,看来我对ShowCursor理解错了
利用全局的钩子对键盘、鼠标进行监控
http://blog.csdn.net/nuaye1949/article/details/4364721
嗯,感谢您的思路,采用UserActivityHook也是一种办法