除了被点击的按钮,更改所有按钮的背景色

3

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

我可以通过硬编码每个按钮来实现此目的,但是这个表单有很多按钮。我相信一定有更有效的方法来做到这一点。

我到目前为止只有这些:

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

         }
    }
}

我可以更改Btn2的背景。如何更改表单中所有其他按钮的背景。有没有想法可以在不必硬编码每个按钮的情况下完成这个任务。


你在 else 语句中尝试使用了 c.BackColor 吗? - Ravi Y
4个回答

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;
}

我不得不将 current.BackColor = Color.GreenYellow; 放在 lastButton = current; 下面,否则如果我连续点击一个按钮两次,它会移除颜色。 - Jonas

0

对2013年@Brett Wolfington的答案进行详细说明...

您可以使用一种简单的方法来减少鼠标button_Click事件方法中的代码。

下面我使用Chgcolor方法,并通过我的button_Click事件中的一行代码调用它。它有助于减少冗余,并在所有检查之后调用current.BackColor = Color.GreenYellow;,现在我可以重复点击1个按钮而不会使颜色消失。

以下示例来自Visual Studio Community 2022

    private Button? lastButton = null;

    private void Chgcolor(Button current) 
    {
        if (lastButton != null)
        {
            lastButton.BackColor = SystemColors.Control;
        }

        lastButton = current;
        current.BackColor = Color.GreenYellow;
    }

    private void Button_Click(object sender, EventArgs e)
    {
        Chgcolor((Button)sender);//call the check color method
    }

    private void Button2_Click(object sender, EventArgs e)
    {
        Chgcolor((Button)sender);//call the check color method
    }

enter image description here


0
如果您的按钮位于面板内,请在foreach中执行以下代码。您将获得pnl2Buttons面板内所有按钮,然后尝试传递要更改背景的按钮的文本名称,其余按钮将具有SeaGreen颜色。
foreach (Button oButton in pnl2Buttons.Controls.OfType<Button>())
{
   if (oButton.Text == clickedButton)
   {
       oButton.BackColor = Color.DodgerBlue;
   }
   else
   {
       oButton.BackColor = Color.SeaGreen;
   }
}

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;
       }
   }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接