KField
KField

Reputation: 151

Show a running timer in a WPF window

I need to show a running timer on the window along with information of a test, such as ID, test name, status, start time, end time, etc.

I really wish that I could have a timer control on the page that tells the user that how long the test has been running.


How would one add a running timer on the page?

In addition, if this is possible, I wish my timer could start from some specific time instead of 00:00:00. The reason I need this is because the user can open this page when the test has been running for a while, and the elapsed time shown on the timer should be (current_time - start_time) and start from here.

If the test start at: 7:00 AM and the user opens the page at 7:05AM and the test is still running, the timer should start from 00:05:00.

Upvotes: 4

Views: 9284

Answers (2)

salman_sali
salman_sali

Reputation: 401

Here is how I achieved this.

Stopwatch watch = new Stopwatch();

private void StartTimer()
{
    new Thread(() =>
    {
        watch.Restart();
        while (watch.IsRunning)
        {
            Dispatcher.Invoke(() =>
            {
                timeText.Text = Math.Round(watch.Elapsed.TotalSeconds, 2).ToString() + "s";
            });
        }

    }).Start();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    //i had to start and stop the timer inside a thread, i was having issues without doing so
    new Thread(() =>
    {
        StartTimer();
        //I was calling an api here
        Dispatcher.Invoke(() =>
        {
            messageText.Text = response.message;
        });
        watch.Stop();
    }).Start();            
}

Upvotes: 0

Scott Solmer
Scott Solmer

Reputation: 3897

Here is a very basic example I threw together.

using System.Windows.Threading;

namespace BasicTimer
{
    public partial class MainWindow : Window
    {
        DispatcherTimer t;
        DateTime start;
        public MainWindow()
        {
            InitializeComponent();
            t = new DispatcherTimer(new TimeSpan(0, 0, 0, 0, 50), DispatcherPriority.Background,
                t_Tick, Dispatcher.CurrentDispatcher); t.IsEnabled = true;
            start = DateTime.Now;
        }

        private void t_Tick(object sender, EventArgs e)
        {
            TimerDisplay.Text = Convert.ToString(DateTime.Now - start);
        }

MainWindow XAML

<Window x:Class="BasicTimer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="100" Width="200">
    <Grid>
        <TextBlock x:Name="TimerDisplay" HorizontalAlignment="Left"/>
    </Grid>
</Window>

Upvotes: 13

Related Questions