C# 如何用C语言制作秒表,它只显示秒和毫秒?
因此,我想制作一个计时器来实现这一点:每次我单击按钮时,都会发生以下情况: 0.052 0.521 1.621 2.151 但事实并非如此,而是这样: 0.015 0.032 0.112 0.252 这种情况正在发生: 此代码不正确,我等待了很长时间,直到它出现秒C# 如何用C语言制作秒表,它只显示秒和毫秒?,c#,winforms,timer,C#,Winforms,Timer,因此,我想制作一个计时器来实现这一点:每次我单击按钮时,都会发生以下情况: 0.052 0.521 1.621 2.151 但事实并非如此,而是这样: 0.015 0.032 0.112 0.252 这种情况正在发生: 此代码不正确,我等待了很长时间,直到它出现秒 int sec = 0, ms = 1; private void button1_Click(object sender, EventArgs e) { timer1.Start(); listBox1.Ite
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 framework的System.Diagnostics命名空间中的秒表对象。像这样:
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)
您应该使用.Net framework的System.Diagnostics命名空间中的秒表对象。像这样:
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)
GUI线程必须每秒更新label1 1000次?是的,不,用更大的间隔。留出一些时间让线程进行绘制。Windows上的默认计时器分辨率为15.6毫秒。这只是一个表示错误,没有人对中间值感兴趣。你可以保证你的UI每秒至少更新64次,这足以愚弄人的眼睛。只需更新标签,就可以丢失列表框。如果您希望它精确到原子钟,那么请使用实际经过的挂钟时间,这样操作系统中调用Tick事件处理程序的任何延迟都不会起作用。使用Environment.TickCount.GUI线程必须每秒更新label1 1000次吗?是的,不,用更大的间隔。留出一些时间让线程进行绘制。Windows上的默认计时器分辨率为15.6毫秒。这只是一个表示错误,没有人对中间值感兴趣。你可以保证你的UI每秒至少更新64次,这足以愚弄人的眼睛。只需更新标签,就可以丢失列表框。如果您希望它精确到原子钟,那么请使用实际经过的挂钟时间,这样操作系统中调用Tick事件处理程序的任何延迟都不会起作用。使用Environment.TickCount.或使用插值字符串label1.Text=${sw.elapsedmillesons/1000.0}@flkes-如果用户使用C 6.0或使用插值字符串label1.Text=${sw.elapsedmillyseconds/1000.0},则非常好@flkes-如果用户使用的是C 6,那么这很好。