C# 更改除单击的按钮外的所有按钮背景

C# 更改除单击的按钮外的所有按钮背景,c#,winforms,buttonclick,C#,Winforms,Buttonclick,我正在制作一个有很多按钮的表单。当用户单击一个按钮时,背景应改变颜色。如果他们单击窗体上的另一个按钮,则其背景应更改颜色,而上一个按钮的颜色应恢复为原始颜色 我可以通过对每个按钮进行硬编码来实现这一点,但是这个表单有很多按钮。我确信必须有一种更有效的方法来做到这一点 到目前为止,我有这个 foreach (Control c in this.Controls) { if (c is Button) { if (c.Text.Equals("Button 2"))

我正在制作一个有很多按钮的表单。当用户单击一个按钮时,背景应改变颜色。如果他们单击窗体上的另一个按钮,则其背景应更改颜色,而上一个按钮的颜色应恢复为原始颜色

我可以通过对每个按钮进行硬编码来实现这一点,但是这个表单有很多按钮。我确信必须有一种更有效的方法来做到这一点

到目前为止,我有这个

foreach (Control c in this.Controls)
{
    if (c is Button)
    {
        if (c.Text.Equals("Button 2"))
         {
             Btn2.BackColor = Color.GreenYellow;
         }
         else
         {

         }
    }
}

我可以获得Btn2更改的背景。如何更改窗体中所有其他按钮的背景。你知道我如何做到这一点而不必对每个按钮进行硬编码吗。

只要你没有任何控制容器(如面板),这就行了


下面的代码不考虑表单上按钮的数量。只需将
按钮\u Click
方法设置为所有按钮的事件处理程序。当你点击一个按钮时,它的背景会改变颜色。当您单击任何其他按钮时,该按钮的背景将更改颜色,并且先前着色的按钮的背景将恢复为默认背景颜色

// Stores the previously-colored button, if any
private Button lastButton = null;


你有没有试过用c.BackColor做你的其他颜色?
// Stores the previously-colored button, if any
private Button lastButton = null;
// The event handler for all button's who should have color-changing functionality
private void button_Click(object sender, EventArgs e)
{
    // Change the background color of the button that was clicked
    Button current = (Button)sender;
    current.BackColor = Color.GreenYellow;

    // Revert the background color of the previously-colored button, if any
    if (lastButton != null)
        lastButton.BackColor = SystemColors.Control;

    // Update the previously-colored button
    lastButton = current;
}