2016-03-30 82 views
-4

如何在c#(visual studio 2012)中創建秒錶,當您開始在文本框中輸入內容並在按下輸入時停止時啓動?當我開始輸入另一個單詞時,它應該重新開始,然後再按Enter鍵結束,然後顯示爲每個單詞記錄的時間。如何在c#中創建秒錶?

以下示例演示如何使用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); 
    } 
} 
+2

你有什麼特別的問題? –

+0

那麼,基於這個例子,你有什麼嘗試?你卡在哪裏? – David

+0

你有什麼問題? – Guy

回答

0

您可以覆蓋StopWatch,使之適合您的whishes這樣的:

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)); 
    } 
} 

這只是一個可能的方向推。通過一點努力,你應該能夠繼續下去。