自由色彩,无限魅力:www.zyml.net

使用C#编写一个计时器

上一篇 / 下一篇  2008-02-04 15:34:46

查看( 14 ) / 评论( 0 )
  
大家好!好久没有上来了!小生在此向各方豪杰问好!
今天温习了一下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();
  }
时间有限不说了,运行一下看看!

TAG:

我来说两句

(可选)

日历

« 2009-01-04  
    123
45678910
11121314151617
18192021222324
25262728293031

数据统计

  • 访问量: 104401
  • 日志数: 662
  • 图片数: 22
  • 影音数: 169
  • 商品数: 44
  • 文件数: 344
  • 书签数: 20
  • 建立时间: 2007-04-27
  • 更新时间: 2008-10-09

RSS订阅

Open Toolbar