Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom controls in C# Windows Forms mouse event question

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?

like image 715
Razor Avatar asked Dec 07 '08 10:12

Razor


2 Answers

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;
    }
}
like image 60
Jon B Avatar answered Nov 15 '22 04:11

Jon B


I found a simple solution. I just set the enabled property to false on the label and it's fine.

like image 42
Razor Avatar answered Nov 15 '22 05:11

Razor