如何在一定数量的滴答声后或者说在3-4秒钟后停止计时器?
我启动一个计时器,我想要在10个滴答声后或者2-3秒钟后自动停止。
谢谢!
int counter = 0;
然后在每个滴答中,您会将其递增。达到限制后,您可以停止计时器。在您的滴答事件中执行此操作。
counter++;
if(counter ==10) //or whatever your limit is
yourtimer.Stop();
当计时器达到指定的时间间隔(3秒后),将会触发 timer1_Tick()
事件处理程序,您可以在事件处理程序中停止计时器。
Timer timer1 = new Timer();
timer1.Interval = 3000;
timer1.Enabled = true;
timer1.Tick += new System.EventHandler(timer1_Tick);
void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop(); // or timer1.Enabled = false;
}
System.Windows.Forms.Tick
。您可以像这样跟踪计数器及其生存时间。这是使用计时器的标记属性的好方法。这使它可重复使用于其他计时器,并使您的代码通用,而不是针对每个计时器使用全局定义的 int counter
。此代码相当通用,因为您可以将此事件处理程序分配给管理它的生存时间,并将另一个事件处理程序分配给处理计时器创建的特定操作。 System.Windows.Forms.Timer ExampleTimer = new System.Windows.Forms.Timer();
ExampleTimer.Tag = new CustomTimerStruct
{
Counter = 0,
StartDateTime = DateTime.Now,
MaximumSecondsToLive = 10,
MaximumTicksToLive = 4
};
//Note the order of assigning the handlers. As this is the order they are executed.
ExampleTimer.Tick += Generic_Tick;
ExampleTimer.Tick += Work_Tick;
ExampleTimer.Interval = 1;
ExampleTimer.Start();
public struct CustomTimerStruct
{
public uint Counter;
public DateTime StartDateTime;
public uint MaximumSecondsToLive;
public uint MaximumTicksToLive;
}
void Generic_Tick(object sender, EventArgs e)
{
System.Windows.Forms.Timer thisTimer = sender as System.Windows.Forms.Timer;
CustomTimerStruct TimerInfo = (CustomTimerStruct)thisTimer.Tag;
TimerInfo.Counter++;
//Stop the timer based on its number of ticks
if (TimerInfo.Counter > TimerInfo.MaximumTicksToLive) thisTimer.Stop();
//Stops the timer based on the time its alive
if (DateTime.Now.Subtract(TimerInfo.StartDateTime).TotalSeconds > TimerInfo.MaximumSecondsToLive) thisTimer.Stop();
}
void Work_Tick(object sender, EventArgs e)
{
//Do work specifically for this timer
}
我一般会这样说,因为你没有提到哪个计时器,但是它们都有滴答声...所以:
你需要在类中添加一个计数器,例如
int count;
你需要在计时器开始时初始化它,还需要一个类似于日期时间的变量。
DateTime start;
你需要在计时器开始时初始化它:
start = DateTime.Now;
if(count++ == 10 || (DateTime.Now - start).TotalSeconds > 2)
timer.stop()
public partial class meClass : Form
{
private System.Windows.Forms.Timer t;
private int count;
private DateTime start;
public meClass()
{
t = new Timer();
t.Interval = 50;
t.Tick += new EventHandler(t_Tick);
count = 0;
start = DateTime.Now;
t.Start();
}
void t_Tick(object sender, EventArgs e)
{
if (count++ >= 10 || (DateTime.Now - start).TotalSeconds > 10)
{
t.Stop();
}
// do your stuff
}
}
tmrAutoStop.Tag = 0;
然后,每次滴答声都加一...
tmrAutoStop.Tag = int.Parse(tmrAutoStop.Tag.ToString()) + 1;
并检查它是否达到您期望的数字:
if (int.Parse(tmrAutoStop.Tag.ToString()) >= 10)
{
//do timer cleanup
}
if (int.Parse(tmrAutoStop.Tag.ToString()) % 2 == 0)
{
//do something...
}
else
{
//do something else...
}
检查经过的时间(以秒为单位):
int m = int.Parse(tmrAutoStop.Tag.ToString()) * (1000 / tmrAutoStop.Interval);