2011-06-21 60 views
4

我正在創建一個WinForm應用程序,它將一個人的照片與網絡攝像頭結合在一起,並試圖現在創建一個倒計時效果。我有4張圖片,我想循環瀏覽,但這樣做很難完成。每秒更改圖片箱中的圖像C#

我使用秒計時器,但發生的所有事情是應用程序滯後一點,然後顯示最後一個圖像。有人知道我可以做到這一點嗎?

這裏是我的代碼:

 int counter = 0; 
     // start the counter to swap the images 
     tmCountDown.Start(); 
     while (counter < 4) 
     { 
      // holding off picture taking 
     } 
     // reset counter for timer 
     counter = 0; 
     tmCountDown.Stop(); 

    /// <summary> 
    /// timer event to switch between the countdown images 
    /// </summary> 
    /// <param name="sender"></param> 
    /// <param name="e"></param> 
    private void tmCountDown_Tick(object sender, EventArgs e) 
    { 
     counter++; 
     //MessageBox.Show("c:/vrfid/apppics/" + counter + ".jpg"); 
     pbCountDown.Image = new Bitmap("c:/vrfid/apppics/" + counter + ".jpg"); 
    } 
+1

我不看你在哪裏設置定時器的時間間隔...請顯示相應的代碼。 –

+1

你也可以調用圖片框的InvokePaint成員來強制它自己重繪 – tom502

+1

希望你增加計數器。任何方式,做form.update或form.Refresh甚至pictureBox.Refresh或更新方法有時做這項工作。 – Zenwalker

回答

3

Windows Timer類使用消息隊列通知計時器已過期。所以你需要讓消息循環運行,以便獲得正確數量的定時器到期。所以你應該設置計數器變量爲一個類字段,然後你可以在事件處理程序中增加它。像這樣...

// Main Code 
    _counter = 0; 
    tmCountDown.Start(); 

    // Event Handler 
    private void tmCountDown_Tick(object sender, EventArgs e)  
    { 
     _counter++; 
     if (_counter == 4) 
      tmCountDown.Stop(); 
     else 
      pbCountDown.Image = new Bitmap("c:/vrfid/apppics/" + _counter + ".jpg"); 
    } 
6

您應該使用

counter++; 
this.SuspendLayout(); 
pbCountDown.Image = new Bitmap("c:/vrfid/apppics/" + counter + ".jpg"); 
this.ResumeLayout(); 

我測試了它和它的工作,希望它可以幫助你

1

的問題是,你是在一個旋轉計時器運行時的忙碌循環。您應該檢查事件處理程序中的計時器停止條件。

我也有點驚訝,代碼的作品。如果你使用的是System.Windows.Forms.Timer,你甚至不應該進入事件處理程序,所以計數器不應該增加。此外,計數器值未正確檢查或更新。 while循環可以轉換爲無限循環。

1

找到了解決方案,不需要定時器。感謝您的答案。計時器性能

 int counter = 0; 
     // start the counter to swap the images 
     while (counter < 4) 
     { 
      // holding off picture taking 
      counter++; 
      //MessageBox.Show("c:/vrfid/apppics/" + counter + ".jpg"); 
      pbCountDown.Image = new Bitmap("c:/vrfid/apppics/" + counter + ".jpg"); 
      pbCountDown.Refresh(); 
      Thread.Sleep(1000); 
     } 
     // reset counter for timer 
     counter = 0; 
0

SET「間隔= 1000」這意味着你的計時器每1000毫秒耳目一新 ,然後使用如果(第二== 10).....