2017-08-06 108 views
0

我試圖在實時16秒內停止計時器,但我不知道我該怎麼做。如何以秒實時停止計時器c#?

我做了這個小例子:當picturebox1與picturebox2相交時,這個動作激活一個計時器,並且這個計時器必須在16秒內實時顯示picturebox3並且在停止它之後(計時器)(並且picturebox3不會顯示)。

(對不起,我的英語,但西班牙語的StackOverflow沒有太多的信息)。

我使用Windows窗體和C#

private void timer2_Tick(object sender, EventArgs e) 
    { 
     pictureBox7.Hide(); 
     if ((pictureBox3.Bounds.IntersectsWith(pictureBox2.Bounds) && pictureBox2.Visible) || (pictureBox5.Bounds.IntersectsWith(pictureBox2.Bounds) && pictureBox2.Visible)) 
     {     
      puntaje++; 
      this.Text = "Puntaje: " + puntaje; 
      if (puntaje % 5 == 0) 
      { 
       timer3.Enabled=true; 
//This is the part where i want set down the timer3, timer 2 is on 

      } 
     } 
+0

您的計時器是否需要非常準確?正好在16.0000000000秒?如果你不那麼精確,那麼請看'System.Timers.Timer.Elapsed'事件(https://msdn.microsoft.com/en-us/library/system.timers.timer.elapse(v=vs) .110).aspx) – Svek

回答

0

我可以看到這個實現最徹底的方法是使用System.Timers.Timer的間隔參數。

下面的代碼

var timer = new Timer(TimeSpan.FromSeconds(16).TotalMilliseconds) { AutoReset = false }; 
timer.Elapsed += (sender, e) => 
{ 
    Console.WriteLine($"Finished at exactly {timer.Interval} milliseconds"); 
}; 
_timer.Start(); 

TimeSpan.FromSeconds(16).TotalMilliseconds基本上轉換成16000的示例代碼段,但我用的時間跨度靜態方法讓你瞭解它更容易,看起來更具可讀性。

計時器的AutoReset屬性告訴它應該只觸發一次。

調整了代碼

private void timer2_Tick(object sender, EventArgs e) 
{ 
    pictureBox7.Hide(); 
    if ((pictureBox3.Bounds.IntersectsWith(pictureBox2.Bounds) && pictureBox2.Visible) 
     || (pictureBox5.Bounds.IntersectsWith(pictureBox2.Bounds) && pictureBox2.Visible)) 
    {     
     puntaje++; 
     this.Text = "Puntaje: " + puntaje; 
     if (puntaje % 5 == 0) 
     { 
      var timer3 = new Timer(TimeSpan.FromSeconds(16).TotalMilliseconds) { AutoReset = false }; 
      timer3.Elapsed += (sender, e) => 
      { 
       pictureBox3.Visible = true; 
      }; 
      timer3.Start(); 
     } 
    } 
} 

請不要標記回答了這個問題是否能解決您的問題。

+0

我如何在這段代碼中實現這一點?我很困惑... private void timer2_Tick(object sender,EventArgs e){ pictureBox7.Hide(); if((pictureBox3.Bounds.IntersectsWith(pictureBox2.Bounds)&& pictureBox2.Visible)||(pictureBox5.Bounds.IntersectsWith(pictureBox2.Bounds)&& pictureBox2.Visible)) { puntaje ++; this.Text =「Puntaje:」+ puntaje; if(puntaje%5 == 0)timer3.Enabled = true; } } –

+0

@ DannyJ.Parr在您的文章中添加該代碼,以便我可以相應地進行編輯 – DevEstacion

+0

我添加了代碼 –

1

你可以試試這個,你的計時器滴答事件處理程序。 Timespan計算兩個日期之間的經過時間。在這個案例中,從16秒開始,我們用負數來計算。

private void timer1_Tick(object sender, EventArgs e) 
    { 
     TimeSpan ts = dtStart.Subtract(DateTime.Now); 
     if (ts.TotalSeconds <= -16) 
     { 
      timer1.Stop(); 
     } 
    } 

確保您DTSTART(日期時間)被宣佈當您啓動定時器:

timer1.Start(); 
dtStart = DateTime.Now;