Dick Tucker
Dick Tucker

Reputation: 45

How to programmatically set the value of a timer?

I tried reading the documentation for the WinForms Timer class but I didn't understand it well enough. I want to have a timer that counts down from 60 to 0 seconds and a button that manually adds 10 seconds to the timer whenever pressed. My question is: "what do I need to do to programmatically set the 'value' of a timer"?

I realize this is a simple question, but the answer to it has eluded me. I would be really thankful if I could get some help.

Thanks in advance.

Upvotes: 0

Views: 2366

Answers (2)

mmking
mmking

Reputation: 1577

You need another variable to hold the time. The timer will be responsible for the ticking and it will update the time in your variable. So like this:

int timeLeft = 60;

private void timer1_Tick(object sender, EventArgs e)
{
    if (timeLeft > 0)
    {
        timeLeft = timeLeft - 1;
    }
    else
    {
        timer1.Stop();
    }

    textBox1.Text = timeLeft.ToString();
}

private void StartTimer_Click(object sender, EventArgs e)
{
    timer1.Interval = 1000;
    timer1.Start();
}

private void AddTimeButton_Click(object sender, EventArgs e)
{
    timeLeft = timeLeft + 10; 
}

timer1 would be the timer, textBox1 for showing the time left, and the buttons should be self-explanatory.

Upvotes: 1

Bradley Uffner
Bradley Uffner

Reputation: 16991

The timer measures time in milliseconds (1000 = 1 second). If you want something to update every second set the .Interval to 1000. You will need a variable initially set to 60. In the timer's Tick event you will want to decrement that counter by one and update your UI. When you want to start counting down enable the timer with .Enabled = True. When the counter hits 0 disable the timer.

If you let us know what language you are writing this in (C#, VB, etc) someone can probably give you some actual code.

Upvotes: 0

Related Questions