Home > Enterprise >  C# DispatchTimer WPF Countdown Timer
C# DispatchTimer WPF Countdown Timer

Time:10-08

I have a WPF application that includes a countdown timer, I'm stuck with the formatting part of it, I have little to no experience with programming and this is my first time using c#. I want to countdown from 15 minutes using DispatchTimer, but as of now, my timer only counts down from 15 seconds, any ideas?

My countdown timer so far:

 public partial class MainWindow : Window
    {
        private int time = 15;
     

        private DispatcherTimer Timer;
        public MainWindow()
        {
            InitializeComponent();
            Timer = new DispatcherTimer();
            Timer.Interval = new TimeSpan(0,0,1);
            Timer.Tick  = Timer_Tick;
            Timer.Start();
        }

        void Timer_Tick(object sender, EventArgs e) {
            if (time > 0)
            {
                time--;
                TBCountDown.Text = string.Format("{0}:{1}", time / 60, time % 60);
                
            }
            else {
                Timer.Stop();
            }
        }

The output looks like this:

enter image description here

CodePudding user response:

A better approach would be to do it with a TimeSpan rather than an int with a number. Setting the TimeSpan value in the following application will do the countdown as I want.

TimeSpan.FromMinutes for minutes

TimSpan.FromSeconds for seconds

You can check here for more detailed information.

public partial class MainWindow : Window
{
    DispatcherTimer dispatcherTimer;
    TimeSpan time;
    public MainWindow()
    {
        InitializeComponent();

        time = TimeSpan.FromMinutes(15);
        dispatcherTimer = new DispatcherTimer();
        dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
        dispatcherTimer.Tick  = DispatcherTimer_Tick;
        dispatcherTimer.Start();
    }

    private void DispatcherTimer_Tick(object sender, EventArgs e)
    {
        if (time == TimeSpan.Zero) dispatcherTimer.Stop();
        else
        { 
            time = time.Add(TimeSpan.FromSeconds(-1));
            MyTime.Text = time.ToString("c");
        }
    }
}

Xaml Code

   <Grid>
    <TextBlock Name="MyTime" />
</Grid>

CodePudding user response:

You initialise the DispatchTimer with an interval of 1 second: Timer.Interval = new TimeSpan(0,0,1); And every TimerTick you decrement your timefield.

So, timeshould start of with the total number of seconds you want to count down. If you start with 15, your countdown timer will count down from 15 seconds to zero. If you want it to count down for 15minutes, you have to initialise time to 900 (15 x 60'').

  • Related