c#秒表实时更新

本文关键字:实时更新 | 更新日期: 2023-09-27 18:12:14

(我的第一个问题!)嗨,我是c#的初学者。我试图建立一个简单的定时器(在Windows.Forms)。我制作了一个指示时间的标签,并使用StopWatch类(来自system.diagnostics)。启动/停止秒表的触发事件是空格键KeyDown事件。在第二次点击后,秒表停止并标记。文本被分配给秒表。运行值。我想不断更新标签,但我不知道怎么做。如果我在事件本身中设置while(StopWatchName.IsRunning),则事件将无限期地继续,并且不会对第二次点击做出响应。

提前感谢任何想法!

c#秒表实时更新

你可能应该有一个定时器,频繁触发(例如每10毫秒)-启动计时器时,你启动秒表,停止计时器时,你停止秒表。计时器滴答事件将从秒表设置标签的Text属性。

计时器的间隔当然不会是精确的,但这没关系,因为关键是要依靠秒表来进行实际计时。计时器只是用来频繁地更新标签。

您可能想要使用System.Timers。计时器类,以便每隔几秒调用一个函数来更新你的UI与时间流逝的值。

这是一个很好的例子:http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx

基本上,示例中的OnTimedEvent事件函数将在代码中完成此操作。

编辑:约翰是正确的(见评论),你应该使用表单。定时器可以避免线程封送处理。http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx

TimerEventProcessor将是该示例中关注的函数。

下面的例子实例化了一个system .Timer .Timer对象,该对象会触发它的Timer。每两秒(2,000毫秒)经过一个事件,为该事件设置一个事件处理程序,并启动计时器。事件处理程序显示ElapsedEventArgs的值。每次引发SignalTime属性时。(文档)

using System;
using System.Timers;
public class Example
{
   private static System.Timers.Timer aTimer;
   public static void Main()
   {
      SetTimer();
      Console.WriteLine("'nPress the Enter key to exit the application...'n");
      Console.WriteLine("The application started at {0:HH:mm:ss.fff}", DateTime.Now);
      Console.ReadLine();
      aTimer.Stop();
      aTimer.Dispose();
      Console.WriteLine("Terminating the application...");
   }
   private static void SetTimer()
   {
        // Create a timer with a two second interval.
        aTimer = new System.Timers.Timer(2000);
        // Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += OnTimedEvent;
        aTimer.AutoReset = true;
        aTimer.Enabled = true;
    }
    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
                          e.SignalTime);
    }
}
// The example displays output like the following:
//       Press the Enter key to exit the application...
//
//       The application started at 09:40:29.068
//       The Elapsed event was raised at 09:40:31.084
//       The Elapsed event was raised at 09:40:33.100
//       The Elapsed event was raised at 09:40:35.100
//       The Elapsed event was raised at 09:40:37.116
//       The Elapsed event was raised at 09:40:39.116
//       The Elapsed event was raised at 09:40:41.117
//       The Elapsed event was raised at 09:40:43.132
//       The Elapsed event was raised at 09:40:45.133
//       The Elapsed event was raised at 09:40:47.148
//
//       Terminating the application...