紅綠燈類庫,繼承於control主要是timer.elapsed事件的使用
codeusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Timers;
namespace RedGreenLight
{
public class RedGreen : Control
{
//private Timer timer1;
private System.ComponentModel.IContainer components;
public enum lightstate { red, green }
public lightstate state = lightstate.green;
public System.Timers.Timer timer= new System.Timers.Timer(3000);
public RedGreen()
{
timer.Elapsed += new System.Timers.ElapsedEventHandler(TimedEvent);
timer.Start();
timer.Interval = 3000;
}
public void TimedEvent(object obj, ElapsedEventArgs e)
{
if (this.state == lightstate.green)
{
this.state = lightstate.red;
}
else if (this.state == lightstate.red)
{
this.state = lightstate.green;
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics g = e.Graphics;
Brush mybrush = Brushes.DarkGray;
Brush mybrushg = Brushes.Green;
Brush mybrushr = Brushes.Red;
Pen mypen = new Pen(mybrush, 2);
g.DrawEllipse(mypen, 100, 100, 200, 200);
g.DrawEllipse(mypen, 400, 100, 200, 200);
if (this.state == lightstate.green)
{
g.FillEllipse(mybrushg, 100, 100, 200, 200);
}
else if (this.state == lightstate.red)
{
g.FillEllipse(mybrushr, 400, 100, 200, 200);
}
this.Refresh();
}
/*private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.SuspendLayout();
//
// timer1
//
this.timer1.Interval = 1000;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
this.ResumeLayout(false);
this.timer1.Start();
}*/
/*public void timer1_Tick(object sender, EventArgs e)
{
if (this.state == lightstate.green)
{
this.state = lightstate.red;
}
else if (this.state == lightstate.red)
{
this.state = lightstate.green;
}
}*/
}
}