Search code examples
wpfvb.netcountdown

CountDown Timer not stopping


I have gotten the progress bar filling, and once the StartTime has been reached both the progress bar and label telling the % work. I am unable to make another button say "STOP" the Dim Timer isn't allowing me to call to it at all from outside the current function

Looking for any suggestions on making it stop. Ive tried having it contain If

ProgressBar1.Value = Maximum then Timer.Stop() End if

But the timer will keep ticking and will not stop.

Imports System.Threading
Imports System.Windows.Threading.DispatcherTimer
Imports System.Timers
Imports System.Math

Class MainWindow

Private Sub Rectangle_MouseLeftButtonDown(sender As Object, e As MouseButtonEventArgs)
    Me.DragMove()
End Sub

Private Sub button_Click(sender As Object, e As RoutedEventArgs)
    Me.Close()
End Sub

Private Sub ext_button_Click(sender As Object, e As RoutedEventArgs) Handles ext_button.Click
    Me.Close()
End Sub

Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)

    Dim dispatcherTimer = New Threading.DispatcherTimer()



End Sub

Private Sub Timer_Tick(ByVal sender As Object, ByVal e As EventArgs)
    Dim StartTime = (Convert.ToInt32(TextBoxHour1.Text) * 3600 + Convert.ToInt32(TextBoxMinute1.Text) * 60 + Convert.ToInt32(TextBoxSecond1.Text))
    LabelST.Content = "Starting Seconds: " + Convert.ToString(StartTime)
    LabelST2.Content = ProgressBar1.Value
    ProgressBar1.Value = ProgressBar1.Value + 1
    Dim percent As Int32 = Convert.ToString(ProgressBar1.Value / StartTime * 100)
    LabelPercent1.Content = Convert.ToString(Math.Floor(percent)) + "%"




    ' Forcing the CommandManager to raise the RequerySuggested event
    CommandManager.InvalidateRequerySuggested()
End Sub

Private Sub ButtonStart_Click(sender As Object, e As RoutedEventArgs) Handles ButtonStart.Click
    Dim Timer = New Threading.DispatcherTimer()
    Dim StartTime = (Convert.ToInt32(TextBoxHour1.Text) * 3600 + Convert.ToInt32(TextBoxMinute1.Text) * 60 + Convert.ToInt32(TextBoxSecond1.Text))
    AddHandler Timer.Tick, AddressOf Timer_Tick
    Timer.Interval = New TimeSpan(0, 0, 1)
    If ButtonStart.Content = "START" Then
        ProgressBar1.Maximum = StartTime
        Timer.Start()
        LabelPercent1.Content = (StartTime / 100)
    End If
End Sub

Sub ButtonStart_Copy_Click(sender As Object, e As RoutedEventArgs) Handles ButtonStart_Copy.Click

End Sub
End Class

Solution

  • Make a global field IsTimerRunning of boolean type, set it to true when start button is clicked, and set it to false when stop button is clicked. Have the timer tick callback method check this field, and do normal action when it is true, else stops the timer.