Matt Leverich
Matt Leverich

Reputation: 39

Preventing a System.Windows.Forms.Timer from accumulating Intervals?

I'm coding a Family Feud game in C# and after each answer is submitted the 30-second timer is supposed to reset. The problem is I'm accumulating 1-second Intervals so that the counter is counting down faster and faster. I can't figure out how to prevent the Intervals from accumulating. I want it to stay a fixed 1 seconds no matter how many times the button is pressed. Code:

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();
}

Upvotes: 0

Views: 72

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127563

Don't put _timer.Tick += timer_Tick; in the button click code, put it once in the constructor of your form and have that be the only event registration.

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();
    }
}

Upvotes: 1

Related Questions