0

我是 C# 的新手,到目前为止,我一直在四处寻找这种语言,我已经在我的任务中编写了很多程序,但现在我被一件事困住了,我无法用语言解释,但代码可以说明我的意思想要所以我们开始吧,我知道这是一个愚蠢的程序,但它仅用于教育目的:D

Private void change()
        {
anycontrol.BackColor = Color.Gold; // when this function called the control's BackColor will Change to gold
        }
// example
private void TextBox1_Focused(object sender, EventArgs e)
{
Change(); // this suppose to change the color of the controls which is now textbox1 i want it to work on other controls such as buttons progressbars etc
}

现在,在我解释了我的问题之后,我可能会问您是否可以提供帮助,我们将不胜感激。

4

1 回答 1

3

您可以创建一个将ControlColor作为参数的方法,并且任何继承自Control(即TextBoxDropDownListLabel)的东西都可以使用:

void SetControlBackgroundColour(Control control, Color colour)
{
    if (control != null)
    {
        control.BackColor = colour;
    }
}

在您的示例中,您可以像这样使用它:

private void TextBox1_Focused(object sender, EventArgs e)
{
    SetControlBackgroundColour(sender as Control, Color.Gold);
}

作为对评论的回应,您可以在递归方法中使用此方法,该方法将为表单上的每个控件设置背景颜色:

void SetControlBackgroundColourRecursive(Control parentControl, Color colour)
{
    if (parentControl != null)
    {
        foreach (Control childControl in parentControl.Controls)
        {
            SetControlBackgroundColour(childControl, colour);

            SetControlBackgroundColourRecursive(childControl);
        }
    }
}

Form然后在您的方法中对您的对象 ( this)调用此函数Form1_Load(假设调用了表单Form1):

protected void Form1_Load(object sender, EventArgs e)
{
    SetControlBackgroundColourRecursive(this, Color.Gold);
}
于 2013-08-30T10:51:26.400 回答