从本质上讲,你要检查如果光标在控制的范围内。解决方案如下:
(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中的扩展方法,该方法是有帮助的furthur用法if
语句。
的可能重复【如何当鼠标离开的形式检测?](http://stackoverflow.com/questions/279472/how-to-detect-when-the-mouse-leaves-the-form) – 2010-11-13 08:39:01