Apply same event to every project button in a C#

前端 未结 2 1835
傲寒
傲寒 2021-01-27 09:34

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

2条回答
  •  情深已故
    2021-01-27 10:22

    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);
    

提交回复
热议问题