基本上你想检查光标是否在控件的范围内。这是解决方案:
(1) 在窗体中添加一个与Form 大小相同的Panel,并将窗体中的所有控件移动到面板中。修改很简单:打开MyForm.designer.cs,添加面板,将this.Controls.Add(myLabel);等所有语句修改为this.myPanel.Controls.Add(myLabel);。
(2) 处理您添加的面板的MouseEnter 和MouseLeave 事件。
myPanel.MouseEnter += (sender, e) =>
{
//enter
};
myPanel.MouseLeave += (sender, e) =>
{
if (Cursor.Position.X < myPanel.Location.X
|| Cursor.Position.Y < myPanel.Location.Y
|| Cursor.Position.X > myPanel.Location.X + myPanel.Width
|| Cursor.Position.Y > myPanel.Location.Y + myPanel.Height)
{
//out of scope
}
};
(3) 为什么不在步骤 2 中使用Form?为什么我们需要一个大小相同的Panel?自己试试。表单的窄边框会让你发疯。
(4)您可以将步骤2中的if语句做成一个扩展方法,这样有助于进一步的使用。