C#Windows窗体着色随机按钮

时间:2016-08-27 15:02:45

标签: c# windows forms

我在下面放置问号的地方应该写什么?每次都要改变一个按钮的颜色。

我可以保留列表中的名称,但我无法按下背景颜色。

buttonList[rndNumber].Name ??? Back.Color = Color.Red;
int satir, sutun, minute, tik;
List<Button> buttonList = new List<Button>();
Random rnd = new Random();

private void timerRandom_Tick(object sender, EventArgs e)
{
    int rndNumber = rnd.Next(0, satir*sutun);

    // buttonList[rndNumber].Name ??? Back.Color = Color.Red;
    //  should change the color of the buttons I created below
}

int i = 0, j = 0;
private void btnStart_Click(object sender, EventArgs e)
{
    panel.Controls.Clear();

    switch (comboBoxLevel.Text)
    {
        case "1.Seviye":
            satir = 5; sutun = 5; minute = 60000; tik = 5000;
            break;
        case "2.Seviye":
            satir = 7; sutun = 7; minute = 120000; tik = 5000;
            break;
        case "3.Seviye":
            satir = 9; sutun = 9; minute = 1800000; tik = 500;
            break;
        default:
            break;
    }

    for (i = 0; i < satir; i++)
    {
        for (j = 0; j < sutun; j++)
        {
            Button btn = new Button();
            btn.Name = "btn" + i + j;
            // btn.Text = "Button" + i + " , " + j;
            btn.Size = new Size(80, 60);
            btn.Location = new Point(i * 80, j * 60);
            btn.Click += buttonClick;
            panel.Controls.Add(btn);
            buttonList.Add(btn);
        }
    }
    timerRandom.Interval = tik;
    timerRandom.Start();                 
}

2 个答案:

答案 0 :(得分:1)

您需要设置按钮的BackColor property,无需关心Name

buttonList[rndNumber].BackColor = Color.Red;

答案 1 :(得分:0)

创建原始背景颜色:

 for (i = 0; i < satir; i++)
    {
        for (j = 0; j < sutun; j++)
        {
            Button btn = new Button();
            btn.Name = "btn" + i + j;
           // btn.Text = "Button" + i + " , " + j;
            btn.Size = new Size(80, 60);
            btn.BackColor = System.Drawing.Color.AliceBlue;
            btn.Location = new Point(i * 80, j * 60);
            btn.Click += buttonClick;
            panel.Controls.Add(btn);
            buttonList.Add(btn);
        }
    }

要在创建按钮后更改背景颜色,请将以下内容添加到buttonClick方法中:

private void buttonClick(object sender, EventArgs e)
    {
        Button b = (Button)sender;
        b.BackColor = System.Drawing.Color.AliceBlue;
    }

要更改您命名的按钮的背景颜色,请使用:

private void changeColor(string buttonName,System.Drawing.Color newColor)
    {
        Button b = (Button)Controls.Find(buttonName, true)[0];
        b.BackColor = newColor;
    }