Question

I'm trying to create a stopwatch that will allow a numbericupdown to adjust the time as needed. Right now if I change the numbericupdown to "2" while the time is going it will double entire value including what was already timed, which is what I don't want. Is there a way to use stopwatch to doulbe the time starting at when the value changes for the numbericupdown, if so can someone provide an example?

Dim BTStopWatch1 As New Diagnostics.Stopwatch

Private Sub Timer4_Tick(sender As Object, e As EventArgs) Handles Timer4.Tick
    Dim elapsed As TimeSpan = Me.BTStopWatch1.Elapsed
    elapsed = New TimeSpan(elapsed.Ticks * NumericUpDown4.Value)
    lblBnch.Text = String.Format("{0:00}   :   {1:00}   :   {2:00}", Math.Floor(elapsed.TotalHours), elapsed.Minutes, elapsed.Seconds)
End Sub

Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
    Timer4.Start()
    Me.BTStopWatch1.Start()
End Sub

Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
    Timer4.Stop()
    Me.BTStopWatch1.Stop()
End Sub
Was it helpful?

Solution

The problem is on this line:

elapsed = New TimeSpan(elapsed.Ticks * NumericUpDown4.Value)

You are taking the total number of ticks so far multiplied with the value of the NumericUpDown. This will not take the history of the NumericUpDown into consideration.

What you want to do is store the elapsed number of ticks in a variable that is persistent between the calls to Timer4_Tick. Then add one to that variable multiplied with the value from the NumericUpDown in your timer callback. You can do that by storing the variable you called elapsed as an instance variable initialized to zero and use addition rather than multiplication when calculating the new value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top