Panel中的MouseEnter和MouseLeave事件及其子控件

DxC*_*xCK 13 .net c# mouseevent winforms

我有一个Panel包含子控件.

如果我处理PanelMouseEnterMouseLeave事件,并且其子的MouseEnterMouseLeave事件,该事件被触发顺序是:

Panel.MouseEnter
Panel.MouseLeave
Child1.MouseEnter
Child1.MouseLeave
Panel.MouseEnter
Panel.MouseLeave
Run Code Online (Sandbox Code Playgroud)

但我需要以下顺序:

Panel.MouseEnter
Child1.MouseEnter
Child1.MouseLeave
Panel.MouseLeave
Run Code Online (Sandbox Code Playgroud)

那可能吗?

Mat*_*t J 22

如果您不介意创建usercontrol(从面板或您希望的其他父容器派生),请覆盖您父项的OnMouseLeave方法,如下所示:

protected override void OnMouseLeave(EventArgs e)
{

    if(this.ClientRectangle.Contains(this.PointToClient(Control.MousePosition)))
         return;
    else
    {
        base.OnMouseLeave(e);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,事件提升将按所需顺序进行.


Chr*_*isF 5

当鼠标进入子控件时,鼠标"离开"面板,这就是它触发事件的原因.

您可以在面板MouseLeave事件处理程序中添加以下行中的内容:

// Check if really leaving the panel
if (Cursor.Position.X < Location.X ||
    Cursor.Position.Y < Location.Y ||
    Cursor.Position.X > Location.X + Width - 1 ||
    Cursor.Position.Y > Location.Y + Height - 1)
{
    // Do the panel mouse leave code
}
Run Code Online (Sandbox Code Playgroud)


AMi*_*ico 0

我相信是这样。一个用于验证 WinForms 应用程序事件的好工具。

\n

Windows.Forms 事件顺序

\n

http://missico.spaces.live.com/blog/cns!7178D2C79BA0A7E3!186.entry

\n
    \n
  • 使用 Urs Eichmann 编写的 EventSpy 创建。(ftp://missico.net/EventSpy.zip
  • \n
  • 使用 .NET Framework 3.5 并启用 Visual Basic\xe2\x80\x99s 应用程序框架。
  • \n
\n