Duraholiday February 2016

Count down timer in vb.net

In the following code I have a timer that counts down from 5 mins. I am trying to have a visual count down timer in a lbl in mm:ss but the example I used doesn't work. It counts down but doesn't update the lbl until it hits 00:00.

The asker of the following question (were I got the code) said it works perfectly but for me it doesn't at all.

The Example I used

My code:

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    picLogo.SizeMode = PictureBoxSizeMode.StretchImage

    'Timer until update
    tmrUpdate.Interval = 300000 '5 minutes
    TargetDT = DateTime.Now.Add(CountDownFrom)
    tmrUpdate.Enabled = True


End Sub

Private Sub tmrUpdate_Tick(sender As Object, e As EventArgs) Handles tmrUpdate.Tick
    Dim ts As TimeSpan = TargetDT.Subtract(DateTime.Now)
    If ts.TotalMilliseconds > 0 Then
        lblTimer.Text = ts.ToString("mm\:ss")
    Else
        lblTimer.Text = "00:00"
        tmrUpdate.Stop()
    End If



End Sub

Answers


Duraholiday February 2016

Answer:

Using a Async Sub I had the count down timer running while other stuff was going on in the back ground. This way the app could still be used during the Sub Wait() and this code also displayed the count down timer. Used one timer on a 1 sec interval.

Private Async Sub DoStuff()

'Doing stuff

timeUpDate = 599
        tmrUpdate.Start()
        Application.DoEvents()
        Await Task.Run(Sub()
                           Wait()

                       End Sub)
    Loop
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles tmrUpdate.Tick
    Dim hms = TimeSpan.FromSeconds(timeUpDate)
    Dim m = hms.Minutes.ToString
    Dim s = hms.Seconds.ToString

    If timeUpDate > 0 Then
        timeUpDate -= 1
        lblTimer.Text = (m & ":" & s)

    Else

        tmrUpdate.Stop()
        lblTimer.Text = "text"

    End If

End Sub

Private Sub Wait()
    Threading.Thread.Sleep(600000)
End Sub

Post Status

Asked in February 2016
Viewed 3,102 times
Voted 10
Answered 1 times

Search




Leave an answer