使用C#编写一个计时器(OK)
今天发个计时器的代码.对于初学者.挺好的例子.我这里说得仔细点.
1.打开vs.net (2003\2005都可).
2.建立一个Windows应用程序
3.在项目下添加一个类命名为“Time“
4.编写“Time“类得实现代码
5.在窗体中放两个Label控件和一个时钟(Timer)控件
6.编写窗体得Load事件和(Timer)控件的Tick事件
以下是“Time“类得实现代码:(解决方案中添加类!并命名为time.cs 加入以下代码!)
public class Time
{
private int hours; //小时
private int minutes; //分钟
private int seconds; //秒钟
public Time()
{
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
}
public Time(int hours,int minutes,int seconds)
{
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
public void SetHours(int hours)
{
this.hours = hours;
}
public void SetMinutes(int minutes)
{
this.minutes = minutes;
}
public void SetSeconds(int seconds)
{
this.seconds = seconds;
}
public int GetHours()
{
return this.hours;
}
public int GetMinutes()
{
return this.minutes;
}
public int GetSeconds()
{
return this.seconds;
}
public static Time operator (Time time)
{
time.seconds ;
if (time.seconds >= 60)
{
time.minutes ;
time.seconds = 0;
if (time.minutes >= 60)
{
time.hours ;
time.minutes = 0;
time.seconds = 0;
if (time.hours >= 24)
{
time.hours = 0;
time.minutes = 0;
time.seconds = 0;
}
}
}
return new Time(time.hours,time.minutes,time.seconds);
}
}
以下是Load事件和Timer控件的Tick事件处理程序:
private void Form1_Load(object sender, System.EventArgs e)
{
DateTime dtime = DateTime.Now;
int hour = dtime.Hour;
int minute = dtime.Minute;
int second = dtime.Second;
time = new Time(hour,minute,second);
this.label1.Text = "当前时间是:" hour ":" minute ":" second;
this.timer1.Start();
}
private void timer1_Tick(object sender, System.EventArgs e)
{
time ;
this.label2.Text = "时间在流逝:" time.GetHours() ":" time.GetMinutes() ":" time.GetSeconds();
}
最后记得在代码中将类实例化(这步很重要,不然会出错.)
实例化代码:Time time = new Time();
好啦!现在可以运行啦.哈哈!!!