C#-Win Form停止计时器勾选



这是我的Win-Form应用程序的实现,它有一个倒计时计时器:

readonly DateTime myThreshold;
public Form1()
{
InitializeComponent();
myThreshold = Utils.GetDate();
Timer timer = new Timer();
timer.Interval = 1000; //1 second
timer.Tick += new EventHandler(t_Tick);
timer.Start();
//Threshold check - this only fires once insted of each second
if (DateTime.Now.CompareTo(myThreshold) > 0)
{
// STOP THE TIMER
timer.Stop();
}
else
{
//do other stuff
}
}
void t_Tick(object sender, EventArgs e)
{
TimeSpan timeSpan = myThreshold.Subtract(DateTime.Now);
this.labelTimer.Text = timeSpan.ToString("d' Countdown - 'hh':'mm':'ss''");
}

想要的行为是在达到阈值时停止计时器和勾选功能。

现在不会发生这种情况,因为检查在Form1初始化中只执行一次。

是否存在添加此检查的方法,以便在满足条件后立即停止计时器?

如果我们将timer定义为一个类字段(这样就可以从类中的所有方法访问它(,那么我们只需将检查添加到Tick事件本身,并从那里停止计时器:

private Timer timer = new Timer();
void t_Tick(object sender, EventArgs e)
{
// Stop the timer if we've reached the threshold
if (DateTime.Now > myThreshold) timer.Stop();
TimeSpan timeSpan = myThreshold.Subtract(DateTime.Now);
this.labelTimer.Text = timeSpan.ToString("d' Countdown - 'hh':'mm':'ss''");
}

最新更新