窗体上的鼠标离开事件

本文关键字:离开 事件 鼠标 窗体 | 更新日期: 2023-09-27 18:11:41

我在窗体上设置了'mouse leave'事件,我想在鼠标离开可见区域时隐藏窗体。

但这就是我面临的问题。甚至当我将鼠标移动到同一表单上的按钮时,它也会调用'mouse leave'事件,这使得该表单不可见。

这意味着我必须防止事件触发时,将鼠标移动到按钮。但如何?还有其他方法吗?

窗体上的鼠标离开事件

没有简单的方法可以做到这一点。一种方法是检查表单内的所有控件,如果鼠标没有在其中任何一个控件上,这意味着鼠标在表单

之外。

另一种方法是在鼠标离开事件中检查鼠标是否在窗口边界内

很简单…添加这个:

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();
}