使用C#編寫一個計時器(OK)

來源:互聯網
上載者:User

今天發個計時器的代碼.對於初學者.挺好的例子.我這裡說得仔細點.

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();

好啦!現在可以運行啦.哈哈!!!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.