用另一种形式更改按钮的颜色C#

时间:2016-01-21 17:31:50

标签: c# winforms

我有两个名为Form1和Form2的表单。

每个表单都有3个具有相同名称的按钮:Button1,Button2和Button3。

我想要的是当Form1中的每个颜色的按钮被更改,然后表单2中的每个颜色的按钮也被更改。例如,表单1中的按钮1为绿色,因此表单1中的按钮1也为绿色。

我该怎么做?这些是我所做的,它不起作用

Form1中

Form2 form2 = new Form2();    

private void Klik_Click(object sender, EventArgs e)
    {
      counter++;
      if(counter==1)
      {
        Button1.BackColor = Color.Red;
        Button2.BackColor = Color.Red;
        Button3.BackColor = Color.Red;
        form2.Button1.BackColor = Color.Red;
        form2.Button2.BackColor = Color.Red;
        form2.Button3.BackColor = Color.Red;
      }
      if (counter > 1)
      {
        Button1.BackColor = Color.Green;
        Button2.BackColor = Color.Green;
        Button3.BackColor = Color.Green;
        form2.Button1.BackColor = Color.Green;
        form2.Button2.BackColor = Color.Green;
        form2.Button3.BackColor = Color.Green;
        counter = 0;
      }
    }

private void StripMenu_Click(object sender, EventArgs e)
    {
        form2.Show();
    }

1 个答案:

答案 0 :(得分:3)

你可以试试这个:

在form2中创建一个名为ButtonColor的Property public Color ButtonColor = new Color();

在form2_paint方法中添加以下内容

Button1.BackColor = ButtonColor;
Button2.BackColor = ButtonColor;
Button3.BackColor = ButtonColor;

将form1更改为

Form2 form2 = new Form2();    

private void Klik_Click(object sender, EventArgs e)
    {
      counter++;
      if(counter==1)
      {
        Button1.BackColor = Color.Red;
        Button2.BackColor = Color.Red;
        Button3.BackColor = Color.Red;
        form2.ButtonColor = Color.Red;
      }
      if (counter > 1)
      {
        Button1.BackColor = Color.Green;
        Button2.BackColor = Color.Green;
        Button3.BackColor = Color.Green;
        form2.ButtonColor = Color.Green;
        counter = 0;
      }
        form2.Show();
        form2.Refresh();
    }