怎么在c#中编写一个可以使交通信号灯一闪一闪的代码
2个回答
展开全部
namespace 交通灯信号演示
{
public partial class Form1 : Form
{
private Timer tInstance = new Timer();
private Action action; // 执行交通灯闪烁的代理委托
private TrafficLightColor tlColor=TrafficLightColor.Red;
/// <summary>
/// 交通灯枚举
/// </summary>
enum TrafficLightColor
{
Red=1,
Yellow=2,
Green=4
}
public Form1()
{
InitializeComponent();
tInstance.Interval = 500; // 0.5秒间隔
tInstance.Tick += tInstance_Tick;
tInstance.Enabled = true;
action = new Action(Run);
}
/// <summary>
/// Tick事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tInstance_Tick(object sender, EventArgs e)
{
tInstance.Enabled = false;
action.BeginInvoke(null, null);
tInstance.Enabled = true;
}
/// <summary>
/// 控制交通灯闪烁 红->黄->绿
/// </summary>
private void Run()
{
Color cBackbround=Color.Red;
switch (tlColor)
{
case TrafficLightColor.Red:
cBackbround = Color.Red;
tlColor = TrafficLightColor.Green;
break;
case TrafficLightColor.Yellow:
cBackbround = Color.Yellow;
tlColor = TrafficLightColor.Red;
break;
case TrafficLightColor.Green:
cBackbround = Color.Green;
tlColor = TrafficLightColor.Yellow;
break;
default:
cBackbround = Color.Yellow;
break;
}
// 获取当前窗体的设备句柄
Graphics g = this.CreateGraphics();
// 构造矩形对象,横纵坐标分别为100,
// 矩形的宽100高100构成一个正方形,
// 正方形的两个对角的长正好是圆的直径
Rectangle rectE = new Rectangle(100, 100, 100, 100);
// 画圆,直径为100
g.DrawEllipse(new Pen(new SolidBrush(Color.Black)) , rectE);
// 填充圆的表面积颜色
g.FillEllipse(new SolidBrush(cBackbround), rectE);
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询