Windows窗体上的鼠标离开事件

时间:2011-10-18 17:19:46

标签: c# winforms mouseleave

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

但这是我遇到问题的地方。即使我将鼠标移动到同一表格上的按钮,它也会调用鼠标离开'事件,使这种形式不可见。

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

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

它非常简单......添加:

QueryDataSource