1

(我的第一个问题!)嗨,我是 C# 的初学者。我尝试构建一个简单的计时器(在 Windows.Forms 中)。我制作了一个指示时间的标签,并使用了 StopWatch 类(来自 system.diagnostics)。启动/停止秒表的触发事件是空格键 KeyDown 事件。第二次点击后秒表停止,Label.text 被分配给 Stopwatch.Elapsed 值。我想不断更新标签,但我不知道如何。如果我while(StopWatchName.IsRunning)在事件本身中进行,该事件将无限期地继续并且不会响应第二次点击。

提前感谢您的任何想法!

4

3 回答 3

8

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

计时器的时间间隔当然不会是准确的——但这没关系,因为关键是要依靠秒表来进行实际计时。计时器只是在那里经常更新标签。

于 2013-05-06T12:42:59.480 回答
0

您可能会想要使用 System.Timers。Timer 类,以便每隔几秒调用一次函数以使用经过的时间值更新您的 UI。

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

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

编辑:约翰是正确的(见评论)你应该使用 Forms.Timer 你可以避免线程编组。 http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx

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

于 2013-05-06T12:46:17.993 回答
0

下面的示例实例化一个 System.Timers.Timer 对象,该对象每两秒(2,000 毫秒)触发一次 Timer.Elapsed 事件,为该事件设置一个事件处理程序,并启动计时器。事件处理程序在每次引发时显示 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...
于 2020-06-18T06:14:21.250 回答