我在C#中编写了一个Family Feud游戏,并且在每个答案提交后,30秒计时器应该重置。问题是我累积了1秒的间隔,这样计数器就会越来越快地倒计时。我无法弄清楚如何防止间隔累积。无论按下按钮多少次,我希望它保持固定的1秒。 代码:
public System.Windows.Forms.Timer _timer = new System.Windows.Forms.Timer();
public int time = 30;
private void Check_Click(object sender, RoutedEventArgs e)
{
time = 30;
_timer.Tick += timer_Tick;
_timer.Start();
uxLabel1.Content = time.ToString();
//additional code
}
private void timer_Tick(object sender, EventArgs e)
{
_timer.Interval = 1000;
time--;
if (time == 0)
{
_timer.Stop();
strike();
}
uxLabel1.Content = time.ToString();
}
答案 0 :(得分:1)
不要将_timer.Tick += timer_Tick;
放在按钮点击代码中,将其放在表单的构造函数中,并将其作为唯一的事件注册。
public partial class YourForm : Form
{
public YourForm()
{
InitializeComponets();
_timer = new System.Windows.Forms.Timer();
_timer.Tick += timer_Tick;
_timer.Interval = 1000;
}
private System.Windows.Forms.Timer _timer;
private int time = 30;
private void Check_Click(object sender, RoutedEventArgs e)
{
time = 30;
_timer.Start();
uxLabel1.Content = time.ToString();
//additional code
}
private void timer_Tick(object sender, EventArgs e)
{
time--;
if (time == 0)
{
_timer.Stop();
strike();
}
uxLabel1.Content = time.ToString();
}
}