Search code examples
c#visual-studiotimer

How to start a countdown timer event from the click of a button?


so I have coded a timer where you are able to increase the hours, minutes and seconds by separate button click events. My aim was to set the hours, minutes and seconds and when I click a start button, the code will start to countdown. At the moment I can only seem to get the time to countdown as soon as the time is incremented. Anything I have tried has not worked with the start button click event, any idea's?

public partial class Form1 : Form
{
    System.Windows.Forms.Timer timer;
    TimeSpan countdownClock = TimeSpan.Zero;
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        AddTimeToClock(TimeSpan.FromSeconds(10));
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        timer = new System.Windows.Forms.Timer();
        timer.Interval = (int)TimeSpan.FromSeconds(1).TotalMilliseconds;
        timer.Tick += OnTimeEvent;
        DisplayTime();
    }
    private void DisplayTime()
    {
        lblTime.Text = countdownClock.ToString(@"hh\:mm\:ss");
    }
    private void OnTimeEvent(object sender, EventArgs e)
    {
        // Subtract whatever our interval is from the countdownClock
        countdownClock = countdownClock.Subtract(TimeSpan.FromMilliseconds(timer.Interval));

        if (countdownClock.TotalMilliseconds <= 0)
        {
            // Countdown clock has run out, so set it to zero 
            // (in case it's negative), and stop our timer
            countdownClock = TimeSpan.Zero;
            timer.Stop();
        }

        // Display the current time
        DisplayTime();
    }
    private void AddTimeToClock(TimeSpan timeToAdd)
    {
        // Add time to our clock
        countdownClock += timeToAdd;

        // Display the new time
        DisplayTime();

        // Start the timer if it's stopped
        if (!timer.Enabled) timer.Start();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        AddTimeToClock(TimeSpan.FromMinutes(1));
    }

    private void button3_Click(object sender, EventArgs e)
    {
        AddTimeToClock(TimeSpan.FromMinutes(10));
    }

    private void Start_Click(object sender, EventArgs e)
    {

    }
}

I have also tried adding a timer interval scale using this command

private static readonly int timeScale = 6

to adjust the countdownClock in the OnTimeEvent, and multiply by the scale.

countdownClock = countdownClock.Subtract(timeScale * TimeSpan.FromMilliseconds(timer.Interval));


Solution

  • it's your

    // Start the timer if it's stopped
    if (!timer.Enabled) timer.Start();
    

    You are always starting your clock on time incrementation. Start your clock on btn click.