您可以遍历所有控件并更改它们的 .BackColor:
private void ChangeTheme_btn_Click(object sender, EventArgs e)
{
ChangeTheme(this.Controls, Color.Aqua);
}
private void ChangeTheme(Control.ControlCollection controls, Color color)
{
foreach (Control control in controls)
{
if (control.HasChildren)
{
// Recursively loop through the child controls
ChangeTheme(control.Controls, color);
}
else
{
if (control is TextBox textBox)
{
textBox.BackColor = color;
}
else if (control is Button button)
{
button.BackColor = color;
}
// Example (remove this if you are not using Guna UI)
else if (control is Guna.UI2.WinForms.Guna2Button gBbutton)
{
gBbutton.FillColor = color;
}
}
}
}
您可以为每种类型的控件设置单独的颜色,还可以更改其他属性。例如,如果您使用Guna UI,那么您可能需要设置.FillColor 而不是.BackColor。
如果您有多个表格,您可以执行以下操作:
private void MyForm1_form_Load(object sender, EventArgs e)
{
// Add all the controls to the list
foreach (Control item in MyForm1.instance.Controls)
{
listOfAllFormControls.Add(item);
}
foreach (Control item in MyForm2.instance.Controls)
{
listOfAllFormControls.Add(item);
}
}
private void ChangeTheme_btn_Click(object sender, EventArgs e)
{
SetColorThemeToLight(listOfAllFormControls);
}
private readonly List<Control> listOfAllFormControls = new List<Control>();
private void SetColorThemeToLight(List<Control> list)
{
foreach (Control control in list)
{
if (control.HasChildren)
{
// Recursively loop through the child controls
List<Control> controlList = new List<Control>();
foreach (Control item in control.Controls)
{
controlList.Add(item);
}
SetColorThemeToLight(controlList);
}
else
{
switch (control)
{
case TextBox _:
control.BackColor = Color.Blue;
break;
case Button _:
control.BackColor = Color.Blue;
break;
// Example (remove this if you are not using Guna UI)
case Guna.UI2.WinForms.Guna2Button _:
control.BackColor = Color.Blue;
break;
}
}
}
}
我也改用switch case
如果您使用的是 GUNA UI
仅当您使用 Guna 时才需要这样做:
一些 Guna 控件默认有一个子控件,这不适用于上面的代码。例如,Guna2RadioButton 包含一个名为 Guna2CustomRadioButton 的子控件。
因此,如果您使用的是 Guna,这是更新后的代码:
private static void SetColorThemeToDark(List<Control> list)
{
foreach (object control in list)
{
bool pass = false;
Control realControl = (Control)control;
if (realControl.HasChildren)
{
// Recursively loop through the child controls
List<Control> childList = new List<Control>();
foreach (object item in realControl.Controls)
{
childList.Add(item);
}
SetColorThemeToDark(childList);
pass = true;
}
if (!realControl.HasChildren || pass)
{
switch (control)
{
case Button button :
button.BackColor = Color.Red;
button.ForeColor = Color.White;
break;
case Label label:
label.BackColor = Color.Red;
break;
case Guna.UI2.WinForms.Guna2Button guna2Button :
guna2Button.FillColor = Color.Red;
}
}
}
}