2017-08-06 107 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;