Skip to main content
 首页 » 编程设计

c#之如何在 C# 中制作只显示秒和毫秒的秒表

2024年02月05日16qq78292959

所以我想制作一个计时器来执行此操作:每次单击按钮时都会发生这种情况:

0.052

0.521

1.621

2.151

...

但它不是这样的:

0.015

0.032

0.112

0.252

...

这正在发生: picture

这段代码不正确,我等了很长时间,直到它发出一个秒..

int sec = 0, ms = 1; 
private void button1_Click(object sender, EventArgs e) 
{ 
    timer1.Start(); 
    listBox1.Items.Add(label1.Text); 
    timer1.Interval = 1; 
 
} 
 
private void timer1_Tick(object sender, EventArgs e) 
{ 
    ms++; 
    if (ms >= 1000) 
    { 
        sec++; 
        ms = 0; 
 
    } 
    label1.Text = String.Format("{0:0}.{1:000}", sec, ms); 
} 

请您参考如下方法:

您应该使用 .Net 框架的 System.Diagnostics 命名空间中的 Stopwatch 对象。像这样:

System.Diagnostics.Stopwatch sw = new Stopwatch(); 
 
public void button1_Click() 
{ 
    sw.Start;  // start the stopwatch 
    // do work 
    ... 
 
    sw.Stop;  // stop the stopwatch 
 
    // display stopwatch contents 
    label1.Text = string.Format({0}, sw.Elapsed); 
} 

如果你想看到经过的总时间仅以总秒数和毫秒数表示(没有分钟或小时),你可以将最后一行更改为:

label1.Text = string.Format({0}, sw.ElapsedMilliseconds / 1000.0)