单击后更改按钮背面颜色,并在第二次单击后将其更改回来,依此类推

时间:2017-03-24 16:46:25

标签: c# windows visual-studio

大家好我创建10个按钮并添加我的面板。其作品。我想再次点击按钮时更改button.background颜色,我想要转动相同的颜色。 THA

  private void Form1_Load(object sender, EventArgs e)
    { for (int i = 0; i < 10; i++)
        {
            Button button = new Button();
            button.Size = new Size(43, 43);
            button.Tag = i;
            button.Click += new EventHandler(ButtonClickOneEvent);
           button.Location = new Point(60, 60 + (i * 50));
          }
            this.panel1.Controls.Add(button);
        }
    }

    void ButtonClickOneEvent(object sender, EventArgs e)
    {
        MouseEventArgs me = (MouseEventArgs)e
        Button button = sender as Button;
        if (button != null)
        {
            switch ((int)button.Tag)
            {
                case 0:
                    if (me.Clicks >= 2)
                    { 
                        button.BackColor = Color.White;
                    }
                    else
                    {
                        button.BackColor = Color.Red;
                    }
                    break;
                case 1:
                    button.BackColor = Color.Red;
                    break;
                case 3:
                    button.BackColor = Color.Red;
                    break;
            }
        }

    }

1 个答案:

答案 0 :(得分:4)

如果您想要的是在每次点击鼠标时更改背景颜色,您可以执行以下操作:

void ButtonClickOneEvent(object sender, EventArgs e)
{
    Button btn = sender as Button;
    if (btn != null)
    {
         btn.BackColor = (btn.BackColor == Color.White) ? Color.Red : Color.White;
    }
}