Vaaal88
Vaaal88

Reputation: 621

TIMER or STOPWATCH in visual basic 2010

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.

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 :-\

Upvotes: 0

Views: 15445

Answers (2)

Marco Farulli
Marco Farulli

Reputation: 1

The code posted from Georg need a upgrade:

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

Upvotes: 0

Georg Jung
Georg Jung

Reputation: 1167

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:

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

Upvotes: 1

Related Questions