使用 Windows Form Timer 元件以設定的間隔執行程序

摘要:使用 Windows Form Timer 元件以設定的間隔執行程序

出處 :
http://msdn.microsoft.com/zh-tw/library/3tszykws%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1


第一個程式碼範例是以每次遞增一秒的方式來追蹤每天的時間。 它使用了表單上的 ButtonLabelTimer 元件。 Interval 屬性是設為 1000 (相當於一秒)。 Tick 事件中,標籤的標題是設為目前的時間。 按下按鈕後,Enabled 屬性將設定為 false,以防止計時器更新標籤的標題。 下列程式碼範例要求表單必須有名為 Button1Button 控制項、Timer1Timer 控制項和 Label1Label 按制項。

C# 語法
private void InitializeTimer()
{
    // Call this procedure when the application starts.
    // Set to 1 second.
    Timer1.Interval = 1000;
    Timer1.Tick += new EventHandler(Timer1_Tick);

    // Enable timer.
    Timer1.Enabled = true;

    Button1.Text = "Stop";
    Button1.Click += new EventHandler(Button1_Click);
}

private void Timer1_Tick(object Sender, EventArgs e)   
{
   // Set the caption to the current time.
   Label1.Text = DateTime.Now.ToString();
}

private void Button1_Click(object sender, EventArgs e)
{
  if ( Button1.Text == "Stop" )
  {
    Button1.Text = "Start";
    Timer1.Enabled = false;
  }
  else
  {
    Button1.Text = "Stop";
    Timer1.Enabled = true;
  }
}

第二個程式碼範例會每隔 600 毫秒執行一個程序,直到迴圈完成為止。 下列程式碼範例要求表單必須有名為 Button1Button 控制項、Timer1Timer 控制項和 Label1Label 按制項。

C# 語法
// This variable will be the loop counter.
private int counter;

private void InitializeTimer()
{
   // Run this procedure in an appropriate event.
   counter = 0;
   timer1.Interval = 600;
   timer1.Enabled = true;
   // Hook up timer's tick event handler.
   this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
}

private void timer1_Tick(object sender, System.EventArgs e)   
{
   if (counter >= 10) 
   {
      // Exit loop code.
      timer1.Enabled = false;
      counter = 0;
   }
   else
   {
      // Run your procedure here.
      // Increment counter.
      counter = counter + 1;
      label1.Text = "Procedures Run: " + counter.ToString();
      }
}