用c#窗体应用写一个红绿灯
时间: 2024-05-10 13:18:35 浏览: 10
好的,以下是用 C# 窗体应用程序实现红绿灯的代码:
1. 在窗体中添加三个圆形控件,并设置它们的颜色为红、黄、绿。可以使用 `System.Drawing.Color` 类来设置颜色。
2. 添加一个 Timer 控件,并设置 `Interval` 属性为 1000,即每秒钟触发一次 `Timer.Tick` 事件。
3. 在 `Timer.Tick` 事件中编写代码,实现红绿灯的闪烁逻辑。可以使用一个变量来记录当前显示的灯的颜色,然后根据当前颜色切换到下一个颜色。具体的代码如下:
```csharp
public partial class FormTrafficLight : Form
{
private int currentLightIndex = 0;
private Color[] lightColors = { Color.Red, Color.Yellow, Color.Green };
public FormTrafficLight()
{
InitializeComponent();
// 设置灯的颜色
this.circleRed.BackColor = Color.Red;
this.circleYellow.BackColor = Color.Black;
this.circleGreen.BackColor = Color.Black;
// 启动定时器
this.timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
// 切换灯的颜色
this.circleRed.BackColor = Color.Black;
this.circleYellow.BackColor = Color.Black;
this.circleGreen.BackColor = Color.Black;
currentLightIndex = (currentLightIndex + 1) % 3;
if (currentLightIndex == 0)
{
this.circleRed.BackColor = lightColors[0];
}
else if (currentLightIndex == 1)
{
this.circleYellow.BackColor = lightColors[1];
}
else if (currentLightIndex == 2)
{
this.circleGreen.BackColor = lightColors[2];
}
}
}
```
运行程序,就可以看到红绿灯在交替闪烁了。