正如有人指出的,可以使用 SetWindowsHookEx() 或将 MouseMove 事件挂接到表单中的所有控件上。后者对我来说效果很好。唯一的缺点是,如果您在运行时添加/删除控件,您可能需要另一个解决方案。
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsForms_MouseEvents
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
MouseMove += OnMouseMove;
MouseLeave += OnMouseLeave;
HookMouseMove(this.Controls);
}
private void HookMouseMove(Control.ControlCollection ctls)
{
foreach (Control ctl in ctls)
{
ctl.MouseMove += OnMouseMove;
HookMouseMove(ctl.Controls);
}
}
private void OnMouseMove(object sender, MouseEventArgs e)
{
BackColor = Color.Plum;
Control ctl = sender as Control;
if (ctl != null)
{
// Map mouse coordinate to form
Point loc = this.PointToClient(ctl.PointToScreen(e.Location));
Console.WriteLine("Mouse at {0},{1}", loc.X, loc.Y);
}
}
private void OnMouseLeave(object sender, EventArgs e)
{
BackColor = Color.Gray;
}
}
}
Run Code Online (Sandbox Code Playgroud)