Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling mouseover for multiple controls in same method

Tags:

c#

.net

winforms

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.

like image 766
Zaid Amir Avatar asked Jan 16 '23 08:01

Zaid Amir


2 Answers

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.....;
    }
}
like image 158
xxbbcc Avatar answered Jan 22 '23 14:01

xxbbcc


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));
      }
like image 41
Reed Copsey Avatar answered Jan 22 '23 16:01

Reed Copsey