Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a 30 minute count down timer

Tags:

c#

timer

I want my textbox1.Text to countdown for 30 minutes. So far I have this:

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

    private void button1_Click(object sender, EventArgs e)
    {
        Timer timeX = new Timer();
        timeX.Interval = 1800000;
        timeX.Tick += new EventHandler(timeX_Tick);
    }

    void timeX_Tick(object sender, EventArgs e)
    {
        // what do i put here?
    }
}

However I'm now stumped. I checked Google for answers but couldn't find one matching my question.

like image 508
IceDawg Avatar asked Mar 19 '26 10:03

IceDawg


1 Answers

Here's a simple example similar to the code you posted:

using System;
using System.Windows.Forms;

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

            textBox1.Text = TimeSpan.FromMinutes(30).ToString();
        }

        private void Form1_Load(object sender, EventArgs e) { }

        private void textBox1_TextChanged(object sender, EventArgs e) { }

        private void button1_Click(object sender, EventArgs e)
        {
            var startTime = DateTime.Now;

            var timer = new Timer() { Interval = 1000 };

            timer.Tick += (obj, args) =>    
                textBox1.Text =
                    (TimeSpan.FromMinutes(30) - (DateTime.Now - startTime))
                    .ToString("hh\\:mm\\:ss");

            timer.Enabled = true;
        }
    }
}
like image 92
dharmatech Avatar answered Mar 20 '26 22:03

dharmatech