wpfvb.nettimerinvalidoperationexception

Elapsed Time Event Handler in WPF VB.NET


I'm implementing a timer into my program that starts when a button is pressed. Once the time has elapsed, my intention is to close the program; however, I'm getting an invalid operation exception. I have a different part of my program also using the Close() operation, but even if I remove that from the program, it'll throw the error anyway. How can I make it work properly?

Public Class Password
    Public timer1 As System.Timers.Timer = New System.Timers.Timer()
    Public loginAttempts As Integer = 0
    Private myPassword As String = "MPCgso4char"



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

        wrongPass.Content = "Incorrect password. Please try again."
        wrongPass.Visibility = Visibility.Hidden

        Select Case passTextBox.Text
            Case = myPassword
                Close()
            Case = ""
                wrongPass.Content = "Please enter a valid password."
                wrongPass.Visibility = Visibility.Visible

            Case <> myPassword
                wrongPass.Visibility = Visibility.Visible

        End Select

    End Sub

    Private Sub DeclineButton_Click(sender As Object, e As RoutedEventArgs)
        passTitle.Visibility = Visibility.Hidden
        AcceptButton.Visibility = Visibility.Hidden
        DeclineButton.Visibility = Visibility.Hidden
        showPass.Visibility = Visibility.Hidden
        passTextBox.Visibility = Visibility.Hidden
        If wrongPass.Visibility = Visibility.Visible Then
            wrongPass.Visibility = Visibility.Hidden
        End If

        decBtnClickEvent.Visibility = Visibility.Visible
        timer1.Interval = 1500
        timer1.Enabled = True
        timer1.Start()
        AddHandler timer1.Elapsed, AddressOf TimedEvent

    End Sub

    Private Sub passTextBox_TextChanged(sender As Object, e As TextChangedEventArgs)
        wrongPass.Visibility = Visibility.Hidden
    End Sub

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

    End Sub
    Private Sub TimedEvent(sender As Object, e As System.Timers.ElapsedEventArgs)
        Close()
    End Sub

    Private Sub Enter(sender As Object, e As KeyEventArgs) Handles passTextBox.KeyDown

        If e.Key = Key.Enter Then
            AcceptButton_Click(Nothing, Nothing)
        Else
            Exit Sub
        End If

    End Sub

End Class

Solution

  • Try use Application.Current.Shutdown() instead of Close()

    Private Sub TimedEvent(sender As Object, e As System.Timers.ElapsedEventArgs)
        Application.Current.Shutdown()
    End Sub
    

    In addition be sure that your Public Class Password is't in another thread.

    In this case you can use:

    Me.Dispatcher.Invoke(Sub() Application.Current.Shutdown() End Sub)