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

Posted by cyclotis04 on Stack Overflow See other posts from Stack Overflow or by cyclotis04
Published on 2010-05-19T15:27:59Z Indexed on 2010/05/19 15:30 UTC
Read the original article Hit count: 218

Filed under:
|
|
|
|

I'm attempting to add an event handler for every control on my form. The form is a simple info box which pops up, and clicking anywhere on it does the same thing (sort of like Outlook's email notifier.) To do this, I've written a recursive method to add a MouseClick handler to 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 of the MouseDown and MouseUp events, I'd have to write two more methods. I'm sure there's a way around this, but I can't find it. I want 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);
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET