vb.net Visual Basic 2010 中的计时器或秒表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15119332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TIMER or STOPWATCH in visual basic 2010
提问by Vaaal88
I have little dummy software to test the precision of the stopwatch in visual basic. I've been told that visual basic has a real good timing, but I'm experiencing some strange behaviors.
我几乎没有虚拟软件来测试 Visual Basic 中秒表的精度。有人告诉我,visual basic 的时机非常好,但我遇到了一些奇怪的行为。
This is ALL my code:
这是我的全部代码:
Imports System.IO
Public Class Form1
Public tmrTime As New Stopwatch
Dim currentDate As Date
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
tmrTime.Start()
End Sub
Private Sub Form1_KeyUp(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
TextBox1.Text = (tmrTime.ElapsedTicks / Stopwatch.Frequency) * 1000
End Sub
Private Sub Form1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
TextBox2.Text = (tmrTime.ElapsedTicks / Stopwatch.Frequency) * 1000
End Sub
End Class
The problem si that if I take the non-decimal part of the two textbox (which is the absolute time of pressing and the abs. time of releasing) they are almost ALWAYS coupled, that is BOTH ODD or BOTH EVEN.
问题是,如果我取两个文本框的非小数部分(即按下的绝对时间和释放的绝对时间),它们几乎总是耦合的,即奇数或偶数。
Do you know what's happening?
你知道发生了什么吗?
I have the same result using tmrTime.ElapsedMilliseconds or tmrTime.Elapsed.Ticks :-\
我使用 tmrTime.ElapsedMilliseconds 或 tmrTime.Elapsed.Ticks 得到相同的结果:-\
回答by Georg Jung
There is a good article about StopWatch/Timer precision in .Net here on a MSDN blog. If I correctly understand what you want to do, this should solve your problem:
在MSDN 博客上有一篇关于 .Net 中的秒表/计时器精度的好文章。如果我正确理解您想要做什么,这应该可以解决您的问题:
Public Class Form1
Private _sw As New Stopwatch
Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
_sw.Start()
End Sub
Private Sub Form1_KeyUp(sender As Object, e As KeyEventArgs) Handles MyBase.KeyUp
Dim elapsed As Long
elapsed = _sw.ElapsedTicks
_sw.Stop()
tbTicks.Text = (elapsed / Stopwatch.Frequency) * 1000
_sw.Reset()
End Sub
End Class
回答by Marco Farulli
The code posted from Georg need a upgrade:
从 Georg 发布的代码需要升级:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.KeyPreview = True
End Sub

