5

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

但这是我面临问题的地方。即使我将鼠标移动到同一个表单上的按钮上,它也会调用“鼠标离开”事件,这会使该表单不可见。

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

4

3 回答 3

1

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

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

于 2011-10-18T17:25:57.813 回答
0
// 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();
}
于 2014-06-01T13:28:51.493 回答
0

这很简单......添加这个:

protected override void OnMouseLeave(EventArgs e)
{

    if(this.ClientRectangle.Contains(this.PointToClient(Control.MousePosition)))
         return;
    else
    {
        base.OnMouseLeave(e);
    }
}
于 2016-05-09T15:42:07.203 回答