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

Viewed 57

I am trying to make it so if you hover into a panel, it will change its color, and when you hover into a label, the panel will not change its color or go back to default, let me show pictures of what I am trying to explain:

If you didn't hover into anything, it would be at its default state:

default state

If you hovered into it, panel color will change:

hovered to panel

Then, if you hover into the label, panel color shouldn't change:

hovered to label

But instead, what it does is if you hover into the label, the panel color goes back to what its default was. This is my code:

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

How can I fix this problem? Is there any way to make the code clean or do I have to copy and paste the code and replace words?

1 Answers

You may use the GetChildAtPoint method to check if the mouse cursor is over a child control.

Replace the code in your MouseLeave event handler with the following:

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