Winforms: how to connect an event handler to additional controls

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


i accidentally tried completely 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 is causing a syntax error :

The "System.Windows.Forms.MouseEnter" event can only be displayed on the left side of the + = or - = window

In this example, I want the Panel MouseEnter event to fire if the mouse enters any control on the panel.

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

The code I tried does not compile.

Matters Related

+1
source share
3 answers

Edit:

 ctrl.MouseEnter += panel.MouseEnter; 

to

 ctrl.MouseEnter += panel_MouseEnter; 

Assuming the void panel_MouseEnter method already exists in your code.

I think you need to pass EventHandler as well:

 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 then again, pnlActionCenter_MouseEnter should already exist. It makes sense?

+2
source

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 must be a method, not an event.

This method (which may be an anonymous method) must match the EventHandler signature of the subscriber - void EventHandler(Object sender, EventArgs e) .


Update:

Now I see what you are trying to achieve.

Here is one way to make your code work:

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

You cannot trigger an event. The best you can do is attach the same handler to all events using something like:

 ctrl.MouseEnter += panel1_MouseEnter; 

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

+1
source

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


All Articles