WPF Timer problem… Cannot get correct millisecond tick

前端 未结 3 1789
-上瘾入骨i
-上瘾入骨i 2020-12-04 02:56

I have a basic question regarding timers. My timer is acting very strange. I am trying to make the tick occur every millisecond to update my data. I can get it to work with

3条回答
  •  长情又很酷
    2020-12-04 03:39

    This is the code for C#:

    using System.Windows.Threading;
    
    
    public partial class MainWindow
    {
    
        DateTime Time = new DateTime();
        DispatcherTimer timer1 = new DispatcherTimer();
    
        private void dispatchertimer_Tick(object sender, EventArgs e)
        {
            TimeSpan Difference = DateTime.Now.Subtract(Time);
            Label1.Content = Difference.Milliseconds.ToString();
            Label2.Content = Difference.Seconds.ToString();
            Label3.Content = Difference.Minutes.ToString();
        }
    
        private void Button1_Click(System.Object sender, System.Windows.RoutedEventArgs e)
        {
            timer1.Tick += new System.EventHandler(dispatchertimer_Tick);
            timer1.Interval = new TimeSpan(0, 0, 0);
    
    
            if (timer1.IsEnabled == true)
            {
                timer1.Stop();
            }
            else
            {
                Time = DateTime.Now;
                timer1.Start();
    
            }
        }
    

    Here is how to do it:

    Add 3 labels and 1 button : Label1, Label2, Label3 and Button1

    This is the code for Vb(Visual Basic):

    Imports System.Windows.Threading
    
    Class MainWindow
    
    Dim timer1 As DispatcherTimer = New DispatcherTimer()
    Dim Time As New DateTime
    
    Private Sub dispatchertimer_Tick(ByVal sender As Object, ByVal e As EventArgs)
        Dim Difference As TimeSpan = DateTime.Now.Subtract(Time) 
        Label1.Content = Difference.Milliseconds.ToString
        Label2.Content = Difference.Seconds.ToString
        Label3.Content = Difference.Minutes.ToString
    End Sub
    
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
        AddHandler timer1.Tick, AddressOf dispatchertimer_Tick
        timer1.Interval = New TimeSpan(0, 0, 0)
    
    
        If timer1.IsEnabled = True Then
            timer1.Stop()
        Else
            Time = DateTime.Now
            timer1.Start()
    
        End If
    End Sub
    End Class
    

提交回复
热议问题