2010-09-28

計時器

namespace TimerDemo
{
  public partial class Form1 : Form
  {
   int counter = 0;

   public Form1()
   {
    InitializeComponent();
    timer1.Interval = 1000; // 設定每秒觸發一次
    timer1.Enabled = true; // 啟動 Timer
   }
   private void timer1_Tick(object sender, EventArgs e)
   {
    counter++;
    label1.Text = counter.ToString(); // 讓counter轉換成字串顯示在label1裡
   }
  }
}

小時鐘

namespace TimerDemo
{
 public partial class Form1 : Form
 {
  public Form1()
  {
   InitializeComponent();
   timer1_Tick(this, null); // 讓timer一開始沒有顯示值
   timer1.Interval = 1000; // 設定每秒觸發一次
   timer1.Enabled = true; // 啟動 Timer
  }
  private void timer1_Tick(object sender, EventArgs e)
  {
   DateTime time = DateTime.Now;
   // label1.Text = time.TimeOfDay.ToString();
   // label1.Text = time.Hour + ":" + time.Minute + ":" + time.Second;
   label1.Text = String.Format("{0:00}:{1:00}:{2:00}", 
                  time.Hour, time.Minute, time.Second); // 讓顯示出來的時間格式化
  }
 }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License