2010年Visual Basic中的TIMER或STOPWATCH

时间:2013-02-27 18:17:39

标签: vb.net timer timing stopwatch

我有很少的虚拟软件来测试visual basic中秒表的精度。我被告知视觉基础有一个非常好的时机,但我遇到了一些奇怪的行为。

这是我的所有代码:

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

问题是,如果我取两个文本框的非小数部分(这是按下的绝对时间和释放的绝对时间)它们几乎总是耦合,即两个奇数或两个偶然。< / p>

你知道发生了什么吗?

我使用tmrTime.ElapsedMilliseconds或tmrTime.Elapsed.Ticks获得相同的结果: - \

2 个答案:

答案 0 :(得分:1)

在.Net on a MSDN blog中有关于StopWatch / Timer精度的好文章。如果我正确理解你想做什么,这应该可以解决你的问题:

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

答案 1 :(得分:0)

Georg发布的代码需要升级:

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Me.KeyPreview = True
End Sub