我正在使用C#使用Visual Studio 2013进行项目.我希望计时器从120分钟倒计时到0分钟,当它达到0时,一个消息框将显示时间已到.我还希望在按下重置按钮时重置计时器.但是,当我按下重置按钮时,即使定时器被重置,我按下开始按钮,同时出现消息框"Time up up",定时器也不会启动.请帮我.我是C#的新手,所以请尽量不要给我很难理解的复杂答案.此外,你会看到我更多,因为我会有更多问题要问.谢谢!!(这是我的代码.)
private void startbutton_Click(object sender, EventArgs e)
{
timer.Enabled = true;
foreach (var button in Controls.OfType<Button>())
{
button.Click += button_Click;
timer.Start();
button.BackColor = Color.DeepSkyBlue;
}
}
private void stopandresetbutton_Click(object sender, EventArgs e)
{
button.BackColor = default(Color);
timer.Stop();
timeleft = 0;
timerlabel.Hide();
}
int timeleft = 120;
private void timer_Tick(object sender, EventArgs e)
{
if (timeleft > -1)
{
timerlabel.Text = timeleft + " minutes";
timeleft = timeleft - 1;
}
else
{
timer.Stop();
MessageBox.Show("Time's up!");
}
}
Run Code Online (Sandbox Code Playgroud)
你的错误出在stopandresetbutton_Click方法上。您不应该将 timeLeft 变量设置为 0。因为您想重置计时器,所以应该将其设置为 120(如果您的单位是分钟)。
或者
您在该方法中将 timeLeft 变量设置为 120 startbutton_Click。这样也能发挥作用
为了更好的方法
你可以写一个这样的属性
private int TimeLeft {
get {return timeLeft; }
set {
timeLeft = value;
timerlabel.Text = timeleft + " minutes";
}
}
Run Code Online (Sandbox Code Playgroud)
这样您就可以设置TimeLeft某个值,并且标签的文本也会更改。这是因为在设置 timeLeft 值后您可能不记得更改标签的文本。