Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show a running timer in a WPF window

Tags:

c#

.net

wpf

timer

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.

like image 523
KField Avatar asked Sep 15 '25 11:09

KField


1 Answers

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>
like image 62
Scott Solmer Avatar answered Sep 17 '25 03:09

Scott Solmer