What is the best way to dynamically modify the forecolor and background color of every control of a WinForm application consisting of b开发者_StackOverflow中文版uttons, 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);
}
}
精彩评论