如何在 C# 中创建秒表?
How to create a stopwatch in c#?
如何在 c# (visual studio 2012) 中创建一个秒表,当您开始在文本框中键入内容时启动并在按下 enter 时停止?它应该在我开始输入另一个单词时重新开始,并在按 enter 时再次结束,然后显示为每个单词记录的时间。
以下示例演示了如何使用秒表class 来确定应用程序的执行时间。
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);
}
}
您可以覆盖 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));
}
}
这只是一个可能方向的推动。稍加努力,您应该可以继续。
如何在 c# (visual studio 2012) 中创建一个秒表,当您开始在文本框中键入内容时启动并在按下 enter 时停止?它应该在我开始输入另一个单词时重新开始,并在按 enter 时再次结束,然后显示为每个单词记录的时间。
以下示例演示了如何使用秒表class 来确定应用程序的执行时间。 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);
}
}
您可以覆盖 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));
}
}
这只是一个可能方向的推动。稍加努力,您应该可以继续。