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);
}
You could pass the event name as a string and then use Reflection to implement this, but that would be quite ugly (and slow as well). Unfortunately, there is no other way to pass events as arguments to a method.
However, you can write this elegantly using lambda functions. Instead of writing function to add handler, you can write a function that calls a lambda expression for every control:
Then you can solve your original problem using a single call:
The lambda expression
ctl => { .. }will be called for every control in the tree and inside the lambda expression, you can add handlers to any events of the control. You could also write this using two calls (adding handlers toMouseDownin the first one and toMouseUpin the second one).Compared to solution using Reflection, this is faster and safer.