2012-10-06 67 views
0

可能重複的工作:
How do I enable this timer in C#?獲取該定時器在C#(新手)

我試着去得到一個小項目的運行。當我使用中斷點時,它正確地通過代碼,但是當以正常速度運行程序時,它的運行速度太快。我試圖讓交通燈序列每隔1秒改變一次。這段代碼有什麼問題?它的一個簡單的交通燈序列,使你感興趣:)。新手項目。

} 
     public int counter = 0; 

    private void rbStart_CheckedChanged(object sender, EventArgs e) 
    { 
     Light_timer.Start(); 
     counter++; 

     if (counter == 1) 
     { 
      pbRed.Visible = true; 
      pbAmber.Visible = false; 
      pbGreen.Visible = false; 
     } 
     else if (counter == 2) 
     { 
      pbRed.Visible = true; 
      pbAmber.Visible = true; 
      pbGreen.Visible = false; 
     } 
     else if (counter == 3) 
     { 
      pbRed.Visible = false; 
      pbAmber.Visible = false; 
      pbGreen.Visible = true; 
     } 
     else if (counter == 4) 
     { 
      pbRed.Visible = false; 
      pbAmber.Visible = true; 
      pbGreen.Visible = false; 
     } 
     else if (counter == 5) 
     { 
      pbRed.Visible = true; 
      pbAmber.Visible = false; 
      pbGreen.Visible = false; 
     } 
     else 
     { 
      counter = 0; 
     } 
    } 

    private void rbStop_CheckedChanged(object sender, EventArgs e) 
    { 

     pbRed.Visible = false; 
     pbAmber.Visible = false; 
     pbGreen.Visible = false; 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     Light_timer.Tick += new EventHandler(rbStart_CheckedChanged); 
     Light_timer.Interval = 1000; 
     Light_timer.Stop(); 
    } 

} 

}

+0

是對不起林新。今晚我又看了一遍,認爲我有些地方。我不知道編輯我的舊帖子。 –

+0

這裏肯定有一些故障,但運行速度太快似乎不是其中之一。什麼是設計師綁定的計時器「嘀嗒」事件?也許它被稱爲兩次。 – pilotcam

+0

你解決了我的問題。滴答聲在設計師中與其他東西有關。我一定早就做到了。代碼正如我現在所想的那樣工作:)。出於好奇,你有沒有注意到我可以改進? –

回答

3

你每次連接事件處理程序的計時器到期等等...試試這個:

private void Form1_Load(object sender, EventArgs e) 
{ 
    Light_timer = new Timer(); 
    Light_timer.Tick += new EventHandler(TimerElapsed); 
    Light_timer.Interval = 1000; 
} 

private void TimerElapsed(object sender, EventArgs e) 
{ 
    counter++; 

    if (counter == 1) 
    { 
     pbRed.Visible = true; 
     pbAmber.Visible = false; 
     pbGreen.Visible = false; 
    } 
    else if (counter == 2) 
    { 
     pbRed.Visible = true; 
     pbAmber.Visible = true; 
     pbGreen.Visible = false; 
    } 
    else if (counter == 3) 
    { 
     pbRed.Visible = false; 
     pbAmber.Visible = false; 
     pbGreen.Visible = true; 
    } 
    else if (counter == 4) 
    { 
     pbRed.Visible = false; 
     pbAmber.Visible = true; 
     pbGreen.Visible = false; 
    } 
    else if (counter == 5) 
    { 
     pbRed.Visible = true; 
     pbAmber.Visible = false; 
     pbGreen.Visible = false; 
    } 
    else 
    { 
     counter = 0; 
     Light_timer.Stop(); 
    } 
} 

private void rbStart_CheckedChanged(object sender, EventArgs e) 
{ 
    Light_timer.Start(); 
} 

private void rbStop_CheckedChanged(object sender, EventArgs e) 
{ 
    Light_timer.Stop(); 
    pbRed.Visible = false; 
    pbAmber.Visible = false; 
    pbGreen.Visible = false; 
} 
+0

即使我得到了我的工作,這是更加整潔的代碼。謝謝邁克爾。 :) –