C# – Custom controls in C# Windows Forms mouse event question

ceventswinforms

I have a mouseenter and mouseleave event for a Panel control that changes the backcolor when the mouse enters and goes back to white when it leaves.

I have Label control within this panel as well but when the mouse enters the Label control, the mouseleave event for the panel fires.

This makes sense but how do I keep the backcolor of the Panel the same when the mouse is in its area without the other controls inside affecting it?

Best Answer

You can use GetChildAtPoint() to determine if the mouse is over a child control.

private void panel1_MouseLeave(object sender, EventArgs e)
{
    if (panel1.GetChildAtPoint(panel1.PointToClient(MousePosition)) == null)
    {
        panel1.BackColor = Color.Gray;
    }
}

If the control isn't actually a child control, you can still use MousePosition and PointToScreen to determine if the mouse is still within the bounds of the control.

private void panel1_MouseLeave(object sender, EventArgs e)
{
    Rectangle screenBounds = new Rectangle(this.PointToScreen(panel1.Location), panel1.Size);
    if (!screenBounds.Contains(MousePosition))
    {
        panel1.BackColor = Color.Gray;
    }
}
Related Topic