How to add an event handler to an event by name?

I am trying to add an event handler for each control in my form. The form is a simple info window that appears, and clicking anywhere on it does the same (like an Outlook email reminder.) For this, I wrote a recursive method to add a handler MouseClickfor each control, as follows:

private void AddMouseClickHandler(Control control, MouseEventHandler handler)
{
    control.MouseClick += handler;
    foreach (Control subControl in control.Controls)
        AddMouseClickHandler(subControl, handler);
}

However, if I wanted to add a handler for all events MouseDownand MouseUp, I would have to write two more methods. I am sure there is a way around this, but I cannot find it. I need a method like:

private void AddRecursiveHandler(Control control, Event event, EventHandler handler)
{
    control.event += handler;
    foreach (Control subControl in control.Controls)
        AddRecursiveHandler(subControl, event, handler);
}
0
4

, Reflection, , ( ). , .

, -. , lambda- :

private void TraverseControls(Control control, Action<Control> f) 
{ 
    f(control); 
    foreach (Control subControl in control.Controls) 
        TraverseControls(subControl, f); 
} 

, :

TraverseControls(form, ctl => { 
  ctl.MouseDown += handler;
  ctl.MouseUp += handler); });

lambda ctl => { .. } , . ( MouseDown MouseUp ).

, Reflection, .

+3

, . MSDN

+1

, . FORM MouseDown MouseUp, ,

control.MouseClick += handler... 

, , , .

control.MouseDown += YourFormsMouseDownHandler 
control.MouseUp += YourFormsMouseUpHandler
0
source

If you want an event to occur everywhere, you do not need to add an event to each element. just add the event to the parent form (or the panel, if you want only the elements in the panel to respond), and everything that you click inside this form will fire the event from the parent.

0
source

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


All Articles