整个窗口的MouseHover/MouseLeave事件

10

我有一个表单子类,其中包含MouseHoverMouseLeave的处理程序。当指针位于窗口背景上时,事件可以正常工作,但当指针移动到窗口内部的控件上时,就会引起MouseLeave事件。

是否有任何方法可以覆盖整个窗口的事件。

(.NET 2.0,Visual Studio 2005,Windows XP。)

4个回答

11

重写 MouseLeave 事件以使其在鼠标进入子控件时不触发

    protected override void OnMouseLeave(EventArgs e)
    {
        if (this.ClientRectangle.Contains(this.PointToClient(Control.MousePosition)))
            return;
        else
        {
            base.OnMouseLeave(e);
        }
    }

6

没有好的方法使MouseLeave对容器控件可靠。 使用计时器解决此问题:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        timer1.Interval = 200;
        timer1.Tick += new EventHandler(timer1_Tick);
        timer1.Enabled = true;
    }

    private bool mEntered;

    void timer1_Tick(object sender, EventArgs e) {
        Point pos = this.PointToClient(Cursor.Position);
        bool entered = this.ClientRectangle.Contains(pos);
        if (entered != mEntered) {
            mEntered = entered;
            if (!entered) {
                // Do your leave stuff
                //...
            }
        }
    }
}

6

所以,如果我为窗口内的所有控件(包括面板内部)注册相同的MouseEnter和MouseLeave处理程序,然后让该处理程序检查鼠标位置以检测内部/外部的变化,并调用“真正”的进入/离开处理程序。好主意,谢谢。 - billpg
我添加了一个示例,演示如何仅使用一个MouseEnter和MouseLeave事件来处理整个窗体。如果这对您有用,请告诉我。 - SwDevMan81
好主意。但是如果包含的控件在边框上,它将无效。(在此给予感谢链接)注意到这一点的用户。) - ispiro

0
在您的用户控件上创建一个鼠标悬停事件,例如此类(或其他事件类型)。
private void picBoxThumb_MouseHover(object sender, EventArgs e)
{
    // Call Parent OnMouseHover Event
    OnMouseHover(EventArgs.Empty);
}

在承载用户控件的WinForm上,为了让用户控件处理鼠标悬停事件,请将以下代码放入您的Designer.cs文件中。
this.thumbImage1.MouseHover += new System.EventHandler(this.ThumbnailMouseHover);

在你的WinForm上调用这个方法

private void ThumbnailMouseHover(object sender, EventArgs e)
{

    ThumbImage thumb = (ThumbImage) sender;

}

其中ThumbImage是用户控件的类型


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接