2014-05-23 73 views
0

我該如何做到這一點,如果我點擊按鈕的標誌將是真實的,並在計時器1滴答事件它會改變計數,並會數了起來。如果我再次點擊相同的按鈕,它會倒數。不重置定時器只是爲了保持不變,這取決於標誌是向上還是向下。如果爲真,則應計數,如果爲假,則應計數。 (該標誌在表單頂部設置爲false)。我該如何做到這一點,如果我點擊按鈕,計時器會倒數計數?

現在,它只是計算回來(下)。

這將Timer1蜱事件:

private void timer1_Tick(object sender, EventArgs e) 
     { 
      if (hours == 0 && mins == 0 && secs == 0) 
      { 
       timer1.Stop(); 
       MessageBox.Show(new Form() { TopMost = true }, "Times up!!! :P", "Will you press OK? :P", MessageBoxButtons.OK, MessageBoxIcon.Information); 
       textBox1.Text = "00"; 
       textBox2.Text = "00"; 
       textBox3.Text = "00"; 
       textBox3.Enabled = true; 
       textBox2.Enabled = true; 
       textBox1.Enabled = true; 
       button1.Enabled = true; 
       lblHr.Text = "00"; 
       lblMin.Text = "00"; 
       lblSec.Text = "00"; 
       button2.Enabled = false; 
       button3.Enabled = false; 
      } 
      else 
      { 
       if (secs < 1) 
       { 
        secs = 59; 
        if (mins < 1) 
        { 
         mins = 59; 
         if (hours != 0)0 
          hours -= 1; 
        } 
        else mins -= 1; 

       } 
       else secs -= 1; 
       if (hours > 9) 
        lblHr.Text = hours.ToString(); 
       else lblHr.Text = "0" + hours.ToString(); 
       if (mins > 9) 
        lblMin.Text = mins.ToString(); 
       else lblMin.Text = "0" + mins.ToString(); 
       if (secs > 9) 
        lblSec.Text = secs.ToString(); 
       else lblSec.Text = "0" + secs.ToString(); 
      } 
     } 

private void button4_Click(object sender, EventArgs e) 
     { 
      count_up_down = true; 
     } 

回答

4

首先,改變從小時,分鐘和秒的時間表示爲純seconds。除以秒60和3600設置在標籤上的文字,像這樣:

int hours = totalSeconds/3600; 
int minutes = totalSeconds/60; 
int seconds = totalSeconds % 60; 

添加一個名爲step整數實例變量,並將其設置爲負1

private int step = -1; 

在點擊按鈕,改變在step變量的符號:

step = -step; 

現在,所有你需要做的是改變代碼,使用totalSeconds += step插件tead xyz -= 1 - 你就完成了!

+0

什麼是totalSeconds變量?在我的表單頂部:int小時,分鐘,秒;所以我改變了你寫的小時分鐘秒。但是,我沒有它的totalSeconds變量是什麼。 – user3667377

+0

@ user3667377不,不是。用單個'totalSeconds'替換頂部的小時,分​​鍾和秒,還可以添加'步驟'。每當計時器「滴答」(三個計劃爲局部變量)時,使用答案中的「小時」,「分鐘」和「秒」表達式來設置標籤。 – dasblinkenlight

+0

讓我看看它應該是什麼樣子的完整代碼。謝謝。 – user3667377

0
DateTime start = DateTime.MinValue; 
    TimeSpan oldTime = TimeSpan.Parse("00:00:00"); 
    tm = new Timer(); 
    tm.Tick += new EventHandler(tm_Tick); 

void tm_Tick(object sender, EventArgs e) 
      { 
       TimeSpan runTime = DateTime.Now - start; 
       lblTimer.Text = string.Format("{1:D2}:{2:D2}:{3:D2}", 
               runTime.Days, 
               runTime.Hours, 
               runTime.Minutes, 
               runTime.Seconds); 

      } 

希望上面的代碼能幫助你。