0

我有一些虚拟软件可以在 Visual Basic 中测试秒表的精度。有人告诉我,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

问题在于,如果我采用两个文本框的非小数部分(即按下的绝对时间和释放的绝对时间),它们几乎总是耦合的,即奇数或偶数。

你知道发生了什么吗?

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

4

2 回答 2

1

在 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
于 2013-02-27T21:21:23.657 回答
0

Georg 发布的代码需要升级:

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Me.KeyPreview = True
End Sub
于 2016-04-26T15:41:51.150 回答