悬停在子控件上时如何避免触发 MouseLeave 事件?

How to avoid triggering MouseLeave event when hovering over a child control?

我正在尝试做到这一点,如果您将鼠标悬停在面板上,它会改变颜色,而当您将鼠标悬停在标签上时,面板不会改变其颜色或返回默认设置,让我展示图片我要解释的内容:

如果您没有将鼠标悬停在任何地方,它将处于默认状态:

如果您将鼠标悬停在其中,面板颜色会发生变化:

然后,如果您将鼠标悬停在标签上,面板颜色应该不会改变:

但是,如果您将鼠标悬停在标签中,面板颜色会恢复为默认颜色。这是我的代码:

Private Sub Panel13_MouseEnter(sender As Object, e As EventArgs) Handles Panel13.MouseEnter
    Panel13.BackColor = Color.DarkGreen
End Sub

Private Sub Panel13_MouseLeave(sender As Object, e As EventArgs) Handles Panel13.MouseLeave
    Panel13.BackColor = Color.LimeGreen
End Sub

我该如何解决这个问题?有什么办法可以让代码干净,还是我必须复制粘贴代码并替换文字?

您可以使用 GetChildAtPoint 方法来检查鼠标光标是否在子控件上。

用以下内容替换 MouseLeave 事件处理程序中的代码:

Dim childControl = Panel13.GetChildAtPoint(Panel13.PointToClient(Cursor.Position))
If childControl Is Nothing Then
    Panel13.BackColor = Color.LimeGreen
End If