使用C#编写一个计时器
2024-07-21 02:18:15
供稿:网友
大家好!好久没有上来了!小生在此向各方豪杰问好!
今天温习了一下c#,解决了老大一个难题,以前总是搞不懂重载运算符,也不知道它有什么用处,
今天总算把它给用上了,真有种在深山老林里用上电得感觉,呵呵!我用它做了一个计时器,下面
我就把代码帖出来供大家玩乐一下也好!先把步骤说一下:
1.用.net建立一个windows应用程序
2.在项目下添加一个类命名为“time“
3.编写“time“类得实现代码
4.在窗体中放两个label控件和一个时钟(timer)控件
5.编写窗体得load事件和(timer)控件的tick事件
以下是“time“类得实现代码:
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();
}