2011-05-31 284 views
7

我有一個lblCountdown與60 int值我想使lblCountDown下降的int值以秒直至達到0秒倒計時

這是我到目前爲止有:

private int counter = 60; 
    private void button1_Click(object sender, EventArgs e) 
    { 
     int counter = 60; 
     timer1 = new Timer(); 
     timer1.Tick += new EventHandler(timer1_Tick); 
     timer1.Interval = 1000; // 1 second 
     timer1.Start(); 
     label1.Text = counter.ToString(); 
    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     counter--; 
     if (counter == 0) 

      timer1.Stop(); 
      label1.Text = counter.ToString(); 

    } 

回答

13

使用定時器這個

private System.Windows.Forms.Timer timer1; 
    private int counter = 60; 
    private void btnStart_Click_1(object sender, EventArgs e) 
    { 
     timer1 = new System.Windows.Forms.Timer(); 
     timer1.Tick += new EventHandler(timer1_Tick); 
     timer1.Interval = 1000; // 1 second 
     timer1.Start(); 
     lblCountDown.Text = counter.ToString(); 
    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     counter--; 
     if (counter == 0) 
      timer1.Stop(); 
     lblCountDown.Text = counter.ToString(); 
    } 
+0

pivate定時器定時器1? – Kade 2011-05-31 18:11:42

+0

你需要公開嗎? – Stecya 2011-05-31 18:12:31

+0

我不知道幫我檢查我的代碼 – Kade 2011-05-31 18:13:31

0

您需要Form1的公共類進行初始化。

看到這個代碼:

namespace TimerApp 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private int counter = 60; 
     private void button1_Click(object sender, EventArgs e) 
     { 
      //Insert your code from before 
     } 

     private void timer1_Tick(object sender, EventArgs e) 
     { 
      //Again insert your code 
     } 
    } 
} 

我已經試過這一點,它都能正常運作

如果您需要幫助再隨意發表評論:)

3
int segundo = 0; 
DateTime dt = new DateTime(); 

private void timer1_Tick(object sender, EventArgs e){ 
    segundo++; 
    label1.Text = dt.AddSeconds(segundo).ToString("HH:mm:ss"); 
}