如何在c#中创建秒表?

时间:2016-03-30 11:55:23

标签: c# visual-studio-2012 timer stopwatch

如何在c#(visual studio 2012)中创建秒表,该秒表在您开始输入文本框时开始,在按下Enter时停止?它应该在我开始输入另一个单词时再次开始,然后在按Enter键时再次结束,然后显示为每个单词记录的时间。

以下示例演示如何使用Stopwatch类确定应用程序的执行时间。 C#

using System;
using System.Diagnostics;
using System.Threading;
class Program
{
    static void Main(string[] args)
    {
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();
        Thread.Sleep(10000);
        stopWatch.Stop();
        // Get the elapsed time as a TimeSpan value.
        TimeSpan ts = stopWatch.Elapsed;

        // Format and display the TimeSpan value.
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);
        Console.WriteLine("RunTime " + elapsedTime);
    }
}

1 个答案:

答案 0 :(得分:0)

您可以覆盖StopWatch并使其适合您的情况:

private void Usage()
{
    WordStopWatch wsw = new WordStopWatch();

    // On textchanged?
    wsw.Start();

    // On keypress -> Enter
    wsw.Stop(/*Your control here ala*/ textBoxInput.Something);
}

private class WordStopWatch : Stopwatch
{
    // Temporary save start-time and end-time
    public DateTime StartAt { get; private set; }
    public DateTime EndAt { get; private set; }

    // Save your records
    public List<Tuple<TimeSpan, string>> Records;

    // Override Start() to save StartAt
    public void Start()
    {
        StartAt = DateTime.Now;
        base.Start();
    }

    // Override Stop() to save EndAt and your records.
    public void Stop(string word)
    {
        EndAt = DateTime.Now;
        StartAt = EndAt - base.Elapsed;
        base.Stop();

        Records.Add(new Tuple<TimeSpan, string>(EndAt - StartAt, word));
    }
}

这只是推动一个可能的方向。有点努力,你应该能够继续下去。