I have a project with 3 forms and 10 user controls. Each of these components has around 10 buttons. I would like to use an event to apply a style when they are hovered by the u
You could use a recursive method and call it on your form. It will go through all the child controls of your form, and their children, and if they are a button, it will link them to your centralised method.
Here's an example with a Click event, but it could apply to anything:
private void RecursiveClickSubscribe(Control c)
{
if (c is Button)
{
c.Click += GenericClickHandler;
}
foreach (Control child in c.Controls)
{
RecursiveClickSubscribe(child);
}
}
private void GenericClickHandler(object sender, EventArgs e)
{
// stuff you want to do on every click
}
Form myForm; // one of your three forms.
RecursiveClickSubscribe(MyForm);
Your best option probably would be to subclass the button class, and use that throughout the rest of your code. Reflecting through all your forms and user-defined controls to identify and add an event handler to each button will be costly (both in terms of developer time and run time). Since the Button class isn't sealed, you can easily override the OnMouseHover() method to update the button as needed (making sure to call the base class method before leaving your override).