2013-11-22 61 views
1

我有一個間隔爲1的計時器。每當它打勾時,我想添加時間並將其顯示在我的表單上。使用計時器以秒爲單位的顯示時間

但它有什麼不對。時間更新本身的方式來減慢。如果我將間隔設置爲1000,它可以工作,但我需要它運行得更快。

這裏是我的代碼:

  private void button1_Click_1(object sender, EventArgs e) 
    { 
     timer.Interval = 1; 
     timer.Start(); 
    } 

    private void timer_Tick(object sender, EventArgs e) 
    { 
     lCount++; 
     label1.Text = GetTimeForGUI(lCount); 
    } 

private String GetTimeForGUI(long lTimeInMilliSeconds) 
    { 
     String sGUITime = string.Empty; 
     try 
     { 
      // Get Format: 00:00 
      if (((lTimeInMilliSeconds/1000) % 60) == 0) 
      { 
       sGUITime = Convert.ToString((lTimeInMilliSeconds/1000)/60); 

       // Get the number of digits 
       switch (sGUITime.Length) 
       { 
        case 0: 
         sGUITime = "00:00"; 
         break; 
        case 1: 
         sGUITime = "0" + sGUITime + ":" + "00"; 
         break; 
        case 2: 
         sGUITime = sGUITime + ":" + "00"; 
         break; 
       } 
      } 
      else 
      { 
       long lMinutes; 
       long lSeconds; 

       // Get seconds 
       lTimeInMilliSeconds = lTimeInMilliSeconds/1000; 
       lSeconds = lTimeInMilliSeconds % 60; 
       lMinutes = (lTimeInMilliSeconds - lSeconds)/60; 

       switch (Convert.ToString(lMinutes).Length) 
       { 
        case 0: 
         sGUITime = "00"; 
         break; 
        case 1: 
         sGUITime = "0" + Convert.ToString(lMinutes); 
         break; 
        case 2: 
         sGUITime = Convert.ToString(lMinutes); 
         break;  
       } 

       sGUITime = sGUITime + ":"; 

       switch (Convert.ToString(iSeconds).Length) 
       { 
        case 0: 
         sGUITime = sGUITime + "00"; 
         break; 
        case 1: 
         sGUITime = sGUITime + "0" + Convert.ToString(lSeconds); 
         break; 
        case 2: 
         sGUITime = sGUITime + Convert.ToString(lSeconds); 
         break; 
       } 

      } 

      return sGUITime; 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
      return string.Empty; 
     } 
    } 
+1

這難道不是問題嗎? if(((lTimeInMilliSeconds/1000)%60)== 0) –

+0

它什麼時候更新很慢,間隔爲1或1000?這是有點不清楚你問的。 – Abbas

+0

請告訴我們你正在嘗試做什麼?你想達到什麼目的? –

回答

3

我認爲你正在嘗試做太多自己。使用框架來幫助你。

當計時器和日期時間可用時,不要根據計數器計算自己的秒數。

執行下面會給你秒的標籤(每100毫秒更新)

DateTime startTime; 
    private void button1_Click(object sender, EventArgs e) 
    { 
     timer.Tick += (s, ev) => { label1.Text = String.Format("{0:00}", (DateTime.Now - startTime).Seconds); }; 
     startTime = DateTime.Now; 
     timer.Interval = 100;  // every 1/10 of a second 
     timer.Start(); 
    } 

希望這有助於

0

1表示1毫秒。當你完成GUI更新時,它會再次發射。這是你面臨延遲的原因。我無法弄清楚爲什麼你要每1毫秒更新一次。您需要清楚地發佈您的要求才能獲得更好的答案。

0
// Get seconds 
lTimeInMilliSeconds = lTimeInMilliSeconds/1000; 
lSeconds = lTimeInMilliSeconds % 60; 
lMinutes = (lTimeInMilliSeconds - lSeconds)/60; 

只要你生活在地球上,並使用SI,有1000毫秒在第二,60秒一分鐘,一個小時60分鐘,在一天24小時。

如果基本數學不是您最喜歡的,您應該使用DateTimeTimeSpan

相關問題