Home > OS >  How to start, stop and resume button using timer in wpf C# windows application?
How to start, stop and resume button using timer in wpf C# windows application?

Time:09-10

I am struggling to stop, resume and start the timer using wpf in c# windows application.

I have these button on my xaml but need some logic around c# windows application to achieve this. Secondly, I must have a status bar that will display to the user. When the timer was stop, resume and start as in windows application on my wpf.

How do I create an object in json to serialize this information?

This is my frontend XAML code:

<Window x:Class="PingApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:PingApplication"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="750">
    
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
            <RowDefinition Height="28" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="200" />
        </Grid.ColumnDefinitions>
        <Button Grid.Column="1" Grid.Row="3" HorizontalAlignment="Right" 
            MinWidth="80" Margin="3" Content="Start"  />
        
        <Button Grid.Column="1" Grid.Row="3" HorizontalAlignment="Left" 
            MinWidth="80" Margin="3" Content="Stop"  />
        <Button Grid.Column="1" Grid.Row="3" HorizontalAlignment="Center" 
            MinWidth="80" Margin="3" Content="Resume"  />
        <Label Name="lblTime" FontSize="48" HorizontalAlignment="Center" VerticalAlignment="Center" />
    </Grid>
</Window>

And this is my c# backend code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace PingApplication
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick  = timer_Tick;
            timer.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            lblTime.Content = DateTime.Now.ToLongTimeString();
        }
    }
}
`

CodePudding user response:

dont know about resume but timer.stop();.resume is might be start to

CodePudding user response:

An example of a timer wrapper and its usage:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Input;

namespace Core2022.SO.Juju22Nimza
{
    public class WpfTimer : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler? PropertyChanged;

        private readonly Timer timer = new Timer();

        private readonly Stopwatch stopwatch = new Stopwatch();

        public DateTime Now => DateTime.Now;

        public TimeSpan Elasped => stopwatch.Elapsed;

        public WpfTimer()
        {
            timer.Interval = 50;
            timer.Elapsed  = OnTick;
            timer.Start();
            stopwatch.Start();
        }

        private void OnTick(object? sender, ElapsedEventArgs? e)
        {
            if (PropertyChanged is PropertyChangedEventHandler propertyChanged)
            {
                propertyChanged(this, NowArgs);
                propertyChanged(this, ElaspedArgs);
            }
        }

        public static PropertyChangedEventArgs NowArgs { get; } = new PropertyChangedEventArgs(nameof(Now));
        public static PropertyChangedEventArgs ElaspedArgs { get; } = new PropertyChangedEventArgs(nameof(Elasped));

        public static RoutedUICommand StartCommand { get; } = new RoutedUICommand("Timer Start", "TimerStart", typeof(WpfTimer));
        public static RoutedUICommand ResumeCommand { get; } = new RoutedUICommand("Timer Resume", "TimerResume", typeof(WpfTimer));
        public static RoutedUICommand RestartCommand { get; } = new RoutedUICommand("Timer Restart", "TimerRestart", typeof(WpfTimer));
        public static RoutedUICommand ResetCommand { get; } = new RoutedUICommand("Timer Reset", "TimerReset", typeof(WpfTimer));

        public static ExecutedRoutedEventHandler ExecuteCommand { get; } = (_, e) =>
        {
            if (e.Parameter is WpfTimer timer)
            {
                if (e.Command == StartCommand)
                {
                    timer.stopwatch.Start();
                }
                else if (e.Command == ResumeCommand)
                {
                    timer.stopwatch.Stop();
                }
                else if (e.Command == RestartCommand)
                {
                    timer.stopwatch.Restart();
                }
                else if (e.Command == ResetCommand)
                {
                    timer.stopwatch.Reset();
                }
                else return;
                timer.OnTick(null, null);
            }
        };
        public static CanExecuteRoutedEventHandler CanExecuteCommand { get; } = (_, e) =>
        {
            if (e.Parameter is WpfTimer timer)
            {
                if (e.Command == StartCommand)
                {
                   e.CanExecute = !timer.stopwatch.IsRunning;
                }
                else if (e.Command == ResumeCommand)
                {
                    e.CanExecute = timer.stopwatch.IsRunning;
                }
                else if (e.Command == RestartCommand)
                {
                    e.CanExecute = true;
                }
                else if (e.Command == ResetCommand)
                {
                    e.CanExecute = true;
                }
            }
        };

        public static WpfTimer Default { get; } = new WpfTimer();
    }
}
<Window x:Class="Core2022.SO.Juju22Nimza.WpfTimerWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Core2022.SO.Juju22Nimza"
        mc:Ignorable="d"
        Title="WpfTimerWindow" Height="450" Width="800">
    <Window.CommandBindings>
        <CommandBinding Command="{x:Static local:WpfTimer.StartCommand}"
                        Executed="{x:Static local:WpfTimer.ExecuteCommand}"
                        CanExecute="{x:Static local:WpfTimer.CanExecuteCommand}"/>
        <CommandBinding Command="{x:Static local:WpfTimer.ResetCommand}"
                        Executed="{x:Static local:WpfTimer.ExecuteCommand}"
                        CanExecute="{x:Static local:WpfTimer.CanExecuteCommand}"/>
        <CommandBinding Command="{x:Static local:WpfTimer.RestartCommand}"
                        Executed="{x:Static local:WpfTimer.ExecuteCommand}"
                        CanExecute="{x:Static local:WpfTimer.CanExecuteCommand}"/>
        <CommandBinding Command="{x:Static local:WpfTimer.ResumeCommand}"
                        Executed="{x:Static local:WpfTimer.ExecuteCommand}"
                        CanExecute="{x:Static local:WpfTimer.CanExecuteCommand}"/>
    </Window.CommandBindings>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <StackPanel Grid.Row="1" Orientation="Horizontal">
            <Button Padding="15 5" Margin="5" Content="Start"
                    Command="{x:Static local:WpfTimer.StartCommand}"
                    CommandParameter="{x:Static local:WpfTimer.Default}"/>

            <Button Padding="15 5" Margin="5" Content="Resume"
                    Command="{x:Static local:WpfTimer.ResumeCommand}"
                    CommandParameter="{x:Static local:WpfTimer.Default}"/>

            <Button Padding="15 5" Margin="5" Content="Restart"
                    Command="{x:Static local:WpfTimer.RestartCommand}"
                    CommandParameter="{x:Static local:WpfTimer.Default}"/>
            <Button Padding="15 5" Margin="5" Content="Reset"
                    Command="{x:Static local:WpfTimer.ResetCommand}"
                    CommandParameter="{x:Static local:WpfTimer.Default}"/>
        </StackPanel>
        <StackPanel>
            <TextBlock FontSize="48" HorizontalAlignment="Center" VerticalAlignment="Center" 
                   Text="{Binding Elasped, Source={x:Static local:WpfTimer.Default}}"/>
            <TextBlock FontSize="48" HorizontalAlignment="Center" VerticalAlignment="Center" 
                   Text="{Binding Now, Source={x:Static local:WpfTimer.Default}, StringFormat=T}"/>
        </StackPanel>
    </Grid>
</Window>
  • Related