Ian Boyd
Ian Boyd

Reputation: 256581

Winforms: How to attach an event handler to additional controls

How do i attach the same event handler to additional controls in Winforms/.NET/C#?


i randomly tried perfectly logical code to accomplish what i want, but unfortunately the syntax is not valid in C#:

public MainForm()
{
   InitializeComponent();

   FixPanelMouseEnter(pnlActionCenter);
   FixPanelMouseEnter(pnlAdministrativeTools);
   FixPanelMouseEnter(pnlAutoPlay);
   FixPanelMouseEnter(pnlBackupAndRestore);
   //...snip 49 lines...
   FixPanelMouseEnter(pnlWFirewall);
   FixPanelMouseEnter(pnlWLiveLanguageSettings);
   FixPanelMouseEnter(pnlWUpdate);
}

private void FixPanelMouseEnter(Panel panel)
{
    foreach (Control ctrl in panel.Controls)
        ctrl.MouseEnter += panel.MouseEnter;
}

This invalid code causes the syntax error:

The event 'System.Windows.Forms.MouseEnter' can only appear on the left hand side of a += or -=

In this example i want the Panel's MouseEnter event to fire if the mouse enter's any control in the panel.

How do i attach the same event handler to additional controls in Winforms/.NET/C#?

The code i tried doesn't compile.

Related Questions

Upvotes: 1

Views: 1924

Answers (3)

LarsTech
LarsTech

Reputation: 81610

Change:

ctrl.MouseEnter += panel.MouseEnter;

to

ctrl.MouseEnter += panel_MouseEnter;

Assuming the method void panel_MouseEnter already exists in your code.

I think you need to then pass the EventHandler, too:

private void FixPanelMouseEnter(Panel panel, EventHandler enterMethod) {
  foreach (Control ctrl in panel.Controls)
    ctrl.MouseEnter += enterMethod;
}

and then from your code:

FixPanelMouseEnter(pnlActionCenter, pnlActionCenter_MouseEnter);

But again, the pnlActionCenter_MouseEnter must already exist. Make sense?

Upvotes: 2

Oded
Oded

Reputation: 498904

If your event handler for panel.MouseEnter is called panel_MouseEnter, use this code:

private void FixPanelMouseEnter(Panel panel)
{
    foreach (Control ctrl in panel.Controls)
        ctrl.MouseEnter += panel_MouseEnter;
}

Note that the event handler needs to be a method, not an event.

This method (which could be an anonymous method) need to conform to the EventHandler delegate signature - void EventHandler(Object sender, EventArgs e).


Update:

I see now what you are trying to achieve.

Here is one way to get your code to work:

private void FixPanelMouseEnter(Panel panel, EventHandler commonHandlerForPanel)
{
    foreach (Control ctrl in panel.Controls)
        ctrl.MouseEnter += commonHandlerForPanel;
}

Upvotes: 1

Fredy Treboux
Fredy Treboux

Reputation: 3331

You cannot cause the event to fire. Best thing you can do is attach the same handler to all the events by using something like:

ctrl.MouseEnter += panel1_MouseEnter;

inside your loop, where panel1_MouseEnter is the event handler. It's possible even that you want to do this recursively in case you have nested panels for example.

Upvotes: 1

Related Questions