I am trying to handle mouseover and mouseleave events for multiple controls in the same method. My form has 10 different buttons which I need to handle their mouse events. Now normally I would do something like this:
public Form1()
{
InitializeComponent();
button1.MouseEnter += new EventHandler(button1_MouseEnter);
button1.MouseLeave += new EventHandler(button1_MouseLeave);
}
void button1_MouseLeave(object sender, EventArgs e)
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img1));
}
void button1_MouseEnter(object sender, EventArgs e)
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
}
But since that I have 10 controls which are basically handled the same way, I find it impractical to do a seperate method for each control, in my case its 20 methods that will do almost the same thing but to a different control.
So is there a way to integrate those events into one and just determine which control should be handled.
Edit:
Can thee be a way to determine which exact control raised the event, lets assume that I have a picturebox which changes the image depending on the button being hovered.
Yes, just use the same event handler for all controls when you assign the handlers. Inside the handler, use an if()
to determine which control raised the event.
void SomeEvent_Handler ( object sender, EventArgs e )
{
if ( sender == btn1 ) // event is from btn1
{
btn1....;
}
else if ( sender == checkbox1 ) // event is from checkbox1
{
checkbox1.....;
}
}
You should be able to use the same handler for all of your controls, especially since BackgroundImage is a shared property of Control
, not Button
:
public Form1()
{
InitializeComponent();
button1.MouseEnter += control_MouseEnter;
button1.MouseLeave += control_MouseLeave;
button2.MouseEnter += control_MouseEnter;
button2.MouseLeave += control_MouseLeave;
}
void control_MouseEnter(object sender, EventArgs e)
{
Control control = sender as Control;
if (control != null)
control.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img1));
}
void control_MouseEnter(object sender, EventArgs e)
{
Control control = sender as Control;
if (control != null)
control.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With