2013-11-22 59 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

相关问题