2013-01-22 107 views
3

我正在处理一个有很多按钮的窗体。当用户点击一个按钮时,背景应该改变颜色。如果他们点击表单上的另一个按钮,其背景应该改变颜色,并且以前的按钮颜色应该返回到原始颜色。更改除点击按钮以外的所有按钮背景

我可以通过硬编码在每个按钮中做到这一点,但这种形式有很多按钮。我相信,必须有这样

更有效的方式,我有这个迄今为止

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

     } 
    } 
} 

我可以得到BTN2改变背景。我将如何更改窗体中所有其他按钮的背景。任何想法如何我可以做到这一点,而不必硬编码每个按钮。

+0

你在你的其他尝试c.BackColor? – ryadavilli

回答

4

下面的代码将工作,而不考虑在窗体上按钮的数量。只需将button_Click方法设置为所有按钮的事件处理程序即可。当你点击一个按钮时,它的背景会改变颜色。当你点击任何其他按钮时,该按钮的背景将改变颜色,并且之前彩色的按钮的背景将恢复为默认背景颜色。

// 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; 
} 
+0

谢谢你的工作 – Inkey

0

这只要将作为你没有任何控件容器(如面板)

foreach (Control c in this.Controls) 
{ 
    Button btn = c as Button; 
    if (btn != null) // if c is another type, btn will be null 
    { 
     if (btn.Text.Equals("Button 2")) 
     { 
      btn.BackColor = Color.GreenYellow; 
     } 
     else 
     { 
      btn.BackColor = Color.PreviousColor; 
     } 
    } 
}