colosso
colosso

Reputation: 2525

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?

Upvotes: 0

Views: 3952

Answers (5)

Lloyd Nyahwai
Lloyd Nyahwai

Reputation: 37

Inside mouse in and function remove all the code you have placed and write the one simple line of code below And try it it will work

((Control)sender).BackColor = Color.Red;

Upvotes: 0

VladL
VladL

Reputation: 13043

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

Upvotes: 3

bash.d
bash.d

Reputation: 13217

You could define an EventHandler for MouseIn and MouseOut and then

private void Panel1_MouseIn(object sender, EventArgs e)
{
    Panel p = sender as Panel;
    if(p == panel1){
        //set color  
    }
    else if(p == panel2){
       //set color
    }
...
}  

The same for MouseOut

Upvotes: 1

Catalin M.
Catalin M.

Reputation: 662

You should first cast the sender object to Panel :

Panel panel = sender as Panel;
if (panel == null)
    return;

panel.BackColor = Blue;

Upvotes: 3

Tomtom
Tomtom

Reputation: 9394

You can cast your sender-object to a Panel like

Panel panel = (Panel)sender;
if(panel != null)
// Set the BackColor

Upvotes: 3

Related Questions