编写程序在窗体上放置4个Label控件、4个TextBox控件和1个Button控件。按下按钮控件,3个文本框会依次在绿、黄、红3种颜色之间循环显示。如同十字路口的红绿灯一样。另一个文本框会显示该灯的剩余时间。最初,一个文本框是绿色,其他两个是灰色。每当其中一个文本框显示有颜色时(灯亮),其余两个变为灰色(灯灭)。再按一下按钮,停止循环亮灯和倒计时;再次按下,再循环之前的亮灯和倒计时。其中绿灯的亮灯时间为6秒,黄灯的等待时间为3秒,红灯的亮灯时间为4秒。
时间: 2024-02-11 13:05:00 浏览: 20
好的,我理解了你的要求。以下是实现该功能的示例代码,你可以参考一下:
```csharp
public partial class Form1 : Form
{
private int greenTime = 6; // 绿灯亮的时间
private int yellowTime = 3; // 黄灯亮的时间
private int redTime = 4; // 红灯亮的时间
private int remainTime = 0; // 剩余时间
private int currentLight = 0; // 当前亮的灯的编号,0表示绿灯,1表示黄灯,2表示红灯
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = !timer1.Enabled; // 切换计时器的状态
if (timer1.Enabled)
{
button1.Text = "停止";
currentLight = 0; // 初始为绿灯
remainTime = greenTime;
textBox1.BackColor = Color.Green;
textBox2.BackColor = Color.Gray;
textBox3.BackColor = Color.Gray;
timer1.Interval = 1000; // 计时器每隔1秒触发一次
}
else
{
button1.Text = "开始";
textBox1.BackColor = Color.Gray;
textBox2.BackColor = Color.Gray;
textBox3.BackColor = Color.Gray;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
remainTime--; // 剩余时间减1
if (remainTime == 0) // 如果时间到了
{
switch (currentLight)
{
case 0: // 当前为绿灯
textBox1.BackColor = Color.Gray;
textBox2.BackColor = Color.Yellow;
remainTime = yellowTime;
currentLight = 1; // 切换到黄灯
break;
case 1: // 当前为黄灯
textBox2.BackColor = Color.Gray;
textBox3.BackColor = Color.Red;
remainTime = redTime;
currentLight = 2; // 切换到红灯
break;
case 2: // 当前为红灯
textBox3.BackColor = Color.Gray;
textBox1.BackColor = Color.Green;
remainTime = greenTime;
currentLight = 0; // 切换到绿灯
break;
}
}
textBox4.Text = remainTime.ToString(); // 更新剩余时间文本框
}
}
```
在窗体设计器中,你需要将四个文本框和一个按钮拖放到窗体上,并将它们的名称分别设置为 `textBox1`、`textBox2`、`textBox3`、`textBox4` 和 `button1`。然后,将按钮的 `Click` 事件和计时器的 `Tick` 事件绑定到上述代码中的 `button1_Click` 和 `timer1_Tick` 方法中。这样,当你点击按钮时,就可以开始或停止计时器了。