Handling the mouse for multiple controls in the same method

I am trying to handle mouseover and mouseleave events for multiple controls with the same method. There are 10 different buttons in my form that I need to handle with the mouse. Now I usually 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 then I have 10 controls that are basically handled the same way, I find it inappropriate to make a separate method for each control, in my case there are 20 methods that will do almost the same thing, but with a different control.

So, there is a way to integrate these events into one and simply determine which control should be processed.

Edit:

Can you determine which exact control raised the event, let's say I have an image that changes the image depending on the hover button.

+4
source share
3 answers

Yes, just use the same event handler for all controls when assigning handlers. Inside the handler, use 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.....; } } 
+3
source

You should be able to use the same handler for all of your controls, especially since BackgroundImage is a common Control property, not a 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)); } 
+3
source

Of course, just sign the same method to all your events, and the sender will give you the button that triggered the event.

+2
source

Source: https://habr.com/ru/post/1439216/


All Articles