Search code examples
c#winformspanel

Control hover color


Sorry, this is kinda beginner question but I'm not getting through. I have a Windows Forms Applicaton with 4 panel controls on it. Now I want that the panels change their background when the user hovers with the mouse. I have tried following:

private void Panel1_MouseIn(object sender, EventArgs e)
{
    panel1.BackColor = Color.Red;
}

private void Panel1_MouseOut(object sender, EventArgs e)
{
    panel1.BackColor = Color.Blue;
}

That is working fine, but because I have 4 panels and not one I would have to add 6 more functions like this... The I tried to make one single function for all of them but event sender does not have an accessible BackColor property.

Is there a way to make one single MouseIn function for all panels? If yes, how?


Solution

  • YOu should cast it:

    private void Panel_MouseIn(object sender, EventArgs e)
    {
      Panel pan = sender as Panel;
      pan.BackColor = Color.Red;
    } 
    

    And use this one function for all 4 panels as event handler