-2

I'm currently coding a Timer to start once a button is clicked in Visual Studio using VB.NET. Here's My Code:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Timer1.Enabled = True
    Timer1.Start()
    seconds = +1
    Label2.Text = seconds.ToString

When the program is run and the button is clicked, the timer only moves one integer, and you have to keep on pressing it to make it move. Any ideas?

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
  • You need an event handler for the Timer Tick event and move the code that updates the label and increment your counter to that event http://stackoverflow.com/questions/1142828/add-timer-to-a-windows-forms-application – Steve Jun 26 '15 at 20:04
  • The correct syntax for incrementing is `seconds += 1` and that belongs in the `Tick` event with the `Label2.Text = seconds.ToString` part. – OneFineDay Jun 26 '15 at 20:06
  • if i do that, as soon as the program loads, the timer starts, before the button is even pressed – Arundeep Dhillon Jun 26 '15 at 20:11
  • @ArundeepDhillon You need to make sure the timer is *not* enabled when the form loads. Also, you should be aware that a Windows.Forms.Timer is not guaranteed to fire its Tick event at exactly the interval you set, so you should store the value of `DateTime.Now` as the initial time and use the time since then as the elapsed time. So really you should have the timer interval as something like 200 so ity does not miss the seconds changing by more than an imperceptible amount, and only... – Andrew Morton Jun 26 '15 at 20:47
  • @ArundeepDhillon (continued) update the display (updating the display is usually a relatively expensive operation) if the number of whole seconds has changed. – Andrew Morton Jun 26 '15 at 20:47

1 Answers1

0

Use a StopWatch like this:

Public Class Form1

    Private SW As New Stopwatch

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Timer1.Interval = 1000
        Timer1.Enabled = False
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        SW.Restart()
        Timer1.Start()
        UpdateStopwatch()
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        UpdateStopwatch()
    End Sub

    Private Sub UpdateStopwatch()
        Label2.Text = SW.Elapsed.ToString("hh\:mm\:ss")
    End Sub

End Class
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40