简体   繁体   中英

Set the background color of all objects in C#

Is there an easy way to set the background color of all objects on a form? Im trying to do it through click event when everything is running. So there would be more then one button. What I would like to avoid is having:

changeColor_Click
{
  label1.BackColor = Color.Black;
  label2.BackColor = Color.Black;
  label3.BackColor = Color.Black;
  etc...
}

What I am looking for:

changeColor_Click
{
 all.BackColor = Color.Black;
}

Keep in mind that each label is a different color backgrounds to start on the GUI:

label1 = blue

label2 = red

label3 = yellow

I have a lot of different objects and am trying to find a good way to switch between themes. Any suggestions on how I could achieve this?

You have to use Recursion .

Pardon my lousy c#, have not used it in years, you get the idea...

ChangeColor_Click
{
   ChangeAllBG(this);
}

void ChangeAllBG(Control c)
{
    c.BackColor=Color.Teal;
    foreach (Control ctl in c.Controls)
        ChangeAllBG(ctl);
}
void SetBackColorRecursive(Control control, Color color)
{
    control.BackColor = color;

    foreach (Control c in control.Controls)
        SetBackColorRecursive(c, color);
}

Call this method on your form like this: SetBackColorRecursive(this, Color.Black);

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