我需要一种检测光标何时进入或离开表单的方法。当控件填充表单时,Form.MouseEnter/MouseLeave 不起作用,因此我还必须订阅控件的 MouseEnter 事件(例如表单上的面板)。还有其他方法可以全局跟踪表单光标输入/退出吗?
你可以试试这个:
private void Form3_Load(object sender, EventArgs e)
{
MouseDetector m = new MouseDetector();
m.MouseMove += new MouseDetector.MouseMoveDLG(m_MouseMove);
}
void m_MouseMove(object sender, Point p)
{
Point pt = this.PointToClient(p);
this.Text = (this.ClientSize.Width >= pt.X &&
this.ClientSize.Height >= pt.Y &&
pt.X > 0 && pt.Y > 0)?"In":"Out";
}
MouseDetector 类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;
class MouseDetector
{
#region APIs
[DllImport("gdi32")]
public static extern uint GetPixel(IntPtr hDC, int XPos, int YPos);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool GetCursorPos(out POINT pt);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr GetWindowDC(IntPtr hWnd);
#endregion
Timer tm = new Timer() {Interval = 10};
public delegate void MouseMoveDLG(object sender, Point p);
public event MouseMoveDLG MouseMove;
public MouseDetector()
{
tm.Tick += new EventHandler(tm_Tick); tm.Start();
}
void tm_Tick(object sender, EventArgs e)
{
POINT p;
GetCursorPos(out p);
if (MouseMove != null) MouseMove(this, new Point(p.X,p.Y));
}
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
X = x;
Y = y;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)