简体   繁体   中英

C# - Best way to modify all form controls at once?

What is the best way to dynamically modify the forecolor and background color of every control of a WinForm application consisting of buttons, toolstrips, panels, etc? Is there an easy way to cycle through each control automatically or do I have to manually change each one? Thanks.

You can cycle through controls, I believe that all controls have a Controls property that is a list of contained controls.

Hypothetical function:

public void ChangeControlsColours(Controls in_c)
{

    foreach (Control c in in_c)
    {
        c.BackColor = Colors.Black;
        c.ForeColor = Colors.White;
        if (c.Controls.length >0 ) //I'm not 100% this line is correct, but I think you get the idea, yes?
            ChangeControlsColours(c.Controls)
    }

}
foreach (Control c in MyForm.Controls) {
    c.BackColor = Colors.Black;
    c.ForeColor = Colors.White;
}

It really depends on what you're trying to do. The most elegant way might be a linked application setting you define on design time and you're then be able to change on run time.

    private void UpdateInternalControls(Control parent)
    {
        UpdateControl(parent, delegate(Control control)
                                {
                                    control.BackColor = Color.Turquoise;
                                    control.ForeColor = Color.Yellow;
                                });
    }

    private static void UpdateControl(Control c, Action<Control> action)
    {
        action(c);
        foreach (Control child in c.Controls)
        {
            UpdateControl(child, action);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM