此代码会立即将文本框更改为红色。我想要它,点击按钮然后再点击红色,再点击绿色。
private void button1_Click(object sender, EventArgs e)
{
textBox1.BackColor = System.Drawing.Color.Black;
if (textBox1.BackColor.Equals(System.Drawing.Color.Black))
{
textBox1.BackColor = System.Drawing.Color.Red;
}
if (textBox1.BackColor.Equals(System.Drawing.Color.Red))
{
textBox1.BackColor = System.Drawing.Color.Green;
}
if (textBox1.BackColor.Equals(System.Drawing.Color.Green))
{
textBox1.BackColor = System.Drawing.Color.Blue;
}
if (textBox1.BackColor.Equals(System.Drawing.Color.Blue))
{
textBox1.BackColor = System.Drawing.Color.Red;
}
}
答案 0 :(得分:8)
您始终将颜色设置为黑色。
逻辑最终成为:
Set the color to black.
Is it black? Yes - change to red.
Is it red? Yes - change to green.
Is it green? Yes - change to blue.
Is it blue? Yes - change to red.
不要那样做。
将初始设置移动到类构造函数,并在设置颜色后立即从函数返回(或使用if/elseif/else
构造)。
答案 1 :(得分:6)
您想使用else if
:
if (textBox1.BackColor.Equals(System.Drawing.Color.Black))
{
textBox1.BackColor = System.Drawing.Color.Red;
}
else if (textBox1.BackColor.Equals(System.Drawing.Color.Red))
{
textBox1.BackColor = System.Drawing.Color.Green;
}
else if (textBox1.BackColor.Equals(System.Drawing.Color.Green))
{
textBox1.BackColor = System.Drawing.Color.Blue;
}
else if (textBox1.BackColor.Equals(System.Drawing.Color.Blue))
{
textBox1.BackColor = System.Drawing.Color.Red;
}
您正在做的是将其更改为red
,然后检查它是red
并将其更改为green
。使用else if
,如果if red
,则不会执行black
。
此外,正如Tim在评论中指出的那样,您需要删除行textBox1.BackColor = System.Drawing.Color.Black
,以便在每次点击时都停止black
。在表单的构造函数中将其设置为black
。
答案 2 :(得分:4)
您正在第一行将BackColor设置为黑色,因此您将始终点击第一个案例,它将变为红色。
如果你这么倾向,那么switch语句可能会让你的代码变得更好......
private void button1_Click(object sender, EventArgs e)
{
switch (textBox1.BackColor.ToKnownColor())
{
case KnownColor.Red:
textBox1.BackColor = Color.Green;
break;
case KnownColor.Green:
textBox1.BackColor = Color.Blue;
break;
default:
textBox1.BackColor = Color.Red;
break;
}
}
答案 3 :(得分:1)
您可以创建Queue<Color>
以确定下一个Color
,并在您点击按钮时始终切换它。
private Queue<Color> colors = new Queue<Color>();
public Form1()
{
InitializeComponent();
//Here you set the order that the colors will be set in.
colors.Enqueue(System.Drawing.Color.Black);
colors.Enqueue(System.Drawing.Color.Red);
colors.Enqueue(System.Drawing.Color.Gray);
colors.Enqueue(System.Drawing.Color.Blue);
}
private void button1_Click(object sender, EventArgs e)
{
textbox1.BackColor = colors.Peek();
//move the color at the front to the back of the queue
colors.Enqueue(colors.Dequeue());
}
答案 4 :(得分:0)
这是滑稽的。我测试了这段代码并且它可以正常工作,而不是任何时候对任何人进行记忆,这只是为了愚蠢,因为我们还没有LINQ答案,如果请求我将删除它但是,这里是一个使用内联的示例如果在LINQ语句中找到您要查找的颜色。我提到这件作品吗?
textBox1.BackColor = Color.FromKnownColor(((KnownColor[])Enum.GetValues(typeof(KnownColor)))
.Where(c => c + (textBox1.BackColor == Color.Red ?
(int)KnownColor.DarkSlateBlue : textBox1.BackColor == Color.Green ?
(int)KnownColor.Chartreuse : (int)textBox1.BackColor.ToKnownColor() - (int)KnownColor.Red)
== textBox1.BackColor.ToKnownColor())
.FirstOrDefault());