17

I have a lblCountdown with an int value of 60. I want to make the int value of the lblCountDown decrease with seconds until it reaches 0.

This is what I have so far:

   private int counter = 60;
    private void button1_Click(object sender, EventArgs e)
    {
        int counter = 60;
        timer1 = new Timer();
        timer1.Tick += new EventHandler(timer1_Tick);
        timer1.Interval = 1000; // 1 second
        timer1.Start();
        label1.Text = counter.ToString();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        counter--;
        if (counter == 0)

            timer1.Stop();
            label1.Text = counter.ToString();

    }

6 Answers 6

25

Use Timer for this

   private System.Windows.Forms.Timer timer1; 
   private int counter = 60;
   private void btnStart_Click_1(object sender, EventArgs e)
   {
        timer1 = new System.Windows.Forms.Timer();
        timer1.Tick += new EventHandler(timer1_Tick);
        timer1.Interval = 1000; // 1 second
        timer1.Start();
        lblCountDown.Text = counter.ToString();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        counter--;
        if (counter == 0)
            timer1.Stop();
        lblCountDown.Text = counter.ToString();
    }
2
  • this timer will be not accurate enough. Especially in case of interval will be low. But even with 1 sec interval will be bad. Aug 22, 2020 at 19:02
  • Why will it not be accurate? May 23, 2023 at 22:42
20

(updated 6.6.2020, because of problems with time calculation)

enter image description here

Usage:

CountDownTimer timer = new CountDownTimer();


//set to 30 mins
timer.SetTime(30,0);     

timer.Start();

//update label text
timer.TimeChanged += () => Label1.Text = timer.TimeLeftMsStr; 

// show messageBox on timer = 00:00.000
timer.CountDownFinished += () => MessageBox.Show("Timer finished the work!"); 

//timer step. By default is 1 second
timer.StepMs = 77; // for nice milliseconds time switch

and don't forget to Dispose(); when timer is useless for you;

Source code:

using System;
using System.Diagnostics;
using System.Windows.Forms;

public class CountDownTimer : IDisposable
{
    public Stopwatch _stpWatch = new Stopwatch();

    public Action TimeChanged;
    public Action CountDownFinished;

    public bool IsRunnign => timer.Enabled;

    public int StepMs
    {
        get => timer.Interval;
        set => timer.Interval = value;
    }

    private Timer timer = new Timer();

    private TimeSpan _max = TimeSpan.FromMilliseconds(30000);

    public TimeSpan TimeLeft => (_max.TotalMilliseconds - _stpWatch.ElapsedMilliseconds) > 0 ? TimeSpan.FromMilliseconds(_max.TotalMilliseconds - _stpWatch.ElapsedMilliseconds) : TimeSpan.FromMilliseconds(0);
    
    private bool _mustStop => (_max.TotalMilliseconds - _stpWatch.ElapsedMilliseconds) < 0;

    public string TimeLeftStr => TimeLeft.ToString(@"\mm\:ss");

    public string TimeLeftMsStr => TimeLeft.ToString(@"mm\:ss\.fff");

    private void TimerTick(object sender, EventArgs e)
    {
        TimeChanged?.Invoke();

        if (_mustStop)
        {
            CountDownFinished?.Invoke();
            _stpWatch.Stop();
            timer.Enabled = false;
        }
    }

    public CountDownTimer(int min, int sec)
    {
        SetTime(min, sec);
        Init();
    }

    public CountDownTimer(TimeSpan ts)
    {
        SetTime(ts);
        Init();
    }

    public CountDownTimer()
    {
        Init();
    }

    private void Init()
    {
        StepMs = 1000;
        timer.Tick += new EventHandler(TimerTick);
    }

    public void SetTime(TimeSpan ts)
    {
        _max = ts;
        TimeChanged?.Invoke();
    }

    public void SetTime(int min, int sec = 0) => SetTime(TimeSpan.FromSeconds(min * 60 + sec));

    public void Start() {
        timer.Start();
        _stpWatch.Start();
    }

    public void Pause()
    {
        timer.Stop();
        _stpWatch.Stop();
    }

    public void Stop()
    {
        Reset();
        Pause();
    }

    public void Reset()
    {
        _stpWatch.Reset();
    }

    public void Restart()
    {
        _stpWatch.Reset();
        timer.Start();
    }

    public void Dispose() => timer.Dispose();
}
6
int segundo = 0;
DateTime dt = new DateTime();

private void timer1_Tick(object sender, EventArgs e){
    segundo++;
    label1.Text = dt.AddSeconds(segundo).ToString("HH:mm:ss");
}
0

Here's my solution, it may help someone. You'll need a label & a timer. I wrote it on the form load because I'm working with a personal project, but you may add it's functionality by putting it inside a button.

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

private void timer1_Tick(object sender, EventArgs e){
        if (int.Parse(label_time_left.Text) != 0){
            int futureText = int.Parse(label_time_left.Text) - 1;
            label_time_left.Text = futureText.ToString();
        } else {
            // actions when the timer ends 
        }
}

As you see the way it works it's pretty simple :) Just parsing

-1

Hey please add code in your project,it is easy and i think will solve your problem.

    int count = 10;

    private void timer1_Tick(object sender, EventArgs e)
    {
        count--;
        if (count != 0 && count > 0)
        {
            label1.Text = count / 60 + ":" + ((count % 60) >= 10 ? (count % 60).ToString() : "0" + (count % 60));
        }
        else
        {
            label1.Text = "game over";

        }

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        timer1 = new System.Windows.Forms.Timer();
        timer1.Interval = 1;

        timer1.Tick += new EventHandler(timer1_Tick);

    }
-5

You need a public class for Form1 to initialize.

See this code:

namespace TimerApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private int counter = 60;
        private void button1_Click(object sender, EventArgs e)
        {
            //Insert your code from before
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //Again insert your code
        }
    }
}

I've tried this and it all worked fine

If you need anymore help feel free to comment :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.