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.