我试图制作一个8x8按钮的数组,到目前为止它的工作原理.现在我偶然发现了一个问题.我希望按钮的颜色(背景色)在单击时更改.再次单击时更改为不同的颜色.
到目前为止这是我的代码:
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
Button[,] btn = new Button[8,8];
public Form1()
{
InitializeComponent();
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
btn[x,y] = new Button();
btn[x,y].SetBounds(40 * x, 40 * y, 40, 40);
btn[x,y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(btn[x, y]);
btn[x,y].BackColor = Color.Black;
}
}
/*
btn.Click += new EventHandler(this.btnEvent_click);
btn[x,y].Text = Convert.ToString(x+","+y);
Controls.Add(btn);
btn[x,y].Click += new EventHandler(this.btnEvent_click);
*/
}
private void form1_load(object sender, EventArgs e)
{
}
void btnEvent_click(object sender, EventArgs e)
{
(Control)sender).BackColor = Color.Red;
}
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我只能将颜色更改为红色,并且我尝试了多次if和for语句,以便再次更改颜色.
任何人都可以帮我吗?
嗨临时你可以使用以下解决方案:
void btnEvent_click(object sender, EventArgs e)
{
Control ctrl = ((Control)sender);
switch (ctrl.BackColor.Name)
{
case "Red":
ctrl.BackColor = Color.Yellow;
break;
case "Black":
ctrl.BackColor = Color.White;
break;
case "White":
ctrl.BackColor = Color.Red;
break;
case "Yellow":
ctrl.BackColor = Color.Purple;
break;
default:
ctrl.BackColor = Color.Red;
break;
}
}
Run Code Online (Sandbox Code Playgroud)
我知道也可以有更好的解决方案,但同时你也可以使用它...你可以根据需要在开关声明中添加更多颜色
| 归档时间: |
|
| 查看次数: |
46217 次 |
| 最近记录: |