我已经在Windows表单上设置了“鼠标离开”事件,并且当鼠标离开可见区域时,我想隐藏该表单。
但这就是我面临问题的地方。即使我将鼠标移动到同一表单上的按钮上,它也会调用“鼠标离开”事件,这会使该表单不可见。
这意味着我必须防止在将鼠标移动到按钮时触发该事件。但如何做到呢? 还有其他方法吗?
我已经在Windows表单上设置了“鼠标离开”事件,并且当鼠标离开可见区域时,我想隐藏该表单。
但这就是我面临问题的地方。即使我将鼠标移动到同一表单上的按钮上,它也会调用“鼠标离开”事件,这会使该表单不可见。
这意味着我必须防止在将鼠标移动到按钮时触发该事件。但如何做到呢? 还有其他方法吗?
没有简单的方法来做到这一点。一种方法可能是检查表单内的所有控件,如果鼠标不在任何一个控件上,这意味着鼠标在表单外面。
另一种方法可能是在鼠标离开事件中检查鼠标是否在窗口边界内部。
这非常简单...只需添加这个:
protected override void OnMouseLeave(EventArgs e)
{
if(this.ClientRectangle.Contains(this.PointToClient(Control.MousePosition)))
return;
else
{
base.OnMouseLeave(e);
}
}
// On the form's MouseLeave event, please checking for mouse position is not in each control's client area.
private void TheForm_MouseLeave(object sender, EventArgs e)
{
bool mouse_on_control = false;
foreach (var c in Controls)
mouse_on_control |= c.RectangleToScreen(c.ClientRectangle).Contains(Cursor.Position);
if (!mouse_on_control)
Close();
}
// And in addition, if any control inside has its client area overlapping the form's client area at any border,
// please also checking if mouse position is outside the form's client area on the control's MouseLeave event.
private void ControlOverlappedTheFormsBorder_MouseLeave(object sender, EventArgs e)
{
if (!RectangleToScreen(ClientRectangle).Contains(Cursor.Position))
Close();
}