c#红绿灯窗体程序编写
时间: 2023-10-10 17:06:04 浏览: 70
红绿灯编写程序
以下是一个简单的红绿灯窗体程序示例:
```csharp
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TrafficLight
{
public partial class Form1 : Form
{
private Timer timer;
private int count = 0;
public Form1()
{
InitializeComponent();
// 初始化定时器
timer = new Timer();
timer.Interval = 1000; // 1秒
timer.Tick += new EventHandler(Timer_Tick);
}
private void Timer_Tick(object sender, EventArgs e)
{
count++;
if (count == 1)
{
// 红灯亮,其它灯灭
pictureBoxRed.Image = Properties.Resources.RedOn;
pictureBoxYellow.Image = Properties.Resources.YellowOff;
pictureBoxGreen.Image = Properties.Resources.GreenOff;
}
else if (count == 6)
{
// 红灯灭,黄灯亮
pictureBoxRed.Image = Properties.Resources.RedOff;
pictureBoxYellow.Image = Properties.Resources.YellowOn;
pictureBoxGreen.Image = Properties.Resources.GreenOff;
}
else if (count == 8)
{
// 红灯灭,黄灯灭,绿灯亮
pictureBoxRed.Image = Properties.Resources.RedOff;
pictureBoxYellow.Image = Properties.Resources.YellowOff;
pictureBoxGreen.Image = Properties.Resources.GreenOn;
}
else if (count == 14)
{
// 绿灯灭,黄灯亮
pictureBoxRed.Image = Properties.Resources.RedOff;
pictureBoxYellow.Image = Properties.Resources.YellowOn;
pictureBoxGreen.Image = Properties.Resources.GreenOff;
}
else if (count == 16)
{
// 黄灯灭,红灯亮
pictureBoxRed.Image = Properties.Resources.RedOn;
pictureBoxYellow.Image = Properties.Resources.YellowOff;
pictureBoxGreen.Image = Properties.Resources.GreenOff;
count = 0;
}
}
private void buttonStart_Click(object sender, EventArgs e)
{
// 启动定时器
timer.Start();
}
private void buttonStop_Click(object sender, EventArgs e)
{
// 停止定时器
timer.Stop();
// 灯全部灭
pictureBoxRed.Image = Properties.Resources.RedOff;
pictureBoxYellow.Image = Properties.Resources.YellowOff;
pictureBoxGreen.Image = Properties.Resources.GreenOff;
// 计数器清零
count = 0;
}
}
}
```
在窗体设计器中添加三个 PictureBox 控件,并分别设置红灯、黄灯和绿灯的图片资源。在窗体上添加两个 Button 控件,分别用于启动和停止定时器。
在 Timer_Tick 事件处理程序中,根据计数器的值来控制灯的状态。当计数器为 1 时,红灯亮,其它灯灭;当计数器为 6 时,红灯灭,黄灯亮;当计数器为 8 时,红灯灭,黄灯灭,绿灯亮;当计数器为 14 时,绿灯灭,黄灯亮;当计数器为 16 时,黄灯灭,红灯亮,并将计数器清零。
在启动和停止按钮的 Click 事件处理程序中,分别启动和停止定时器,并将所有灯都灭掉,计数器清零。
阅读全文