WPF 中经过的时间事件处理程序 VB.NET

Elapsed Time Event Handler in WPF VB.NET

我正在我的程序中实现一个计时器,该计时器在按下按钮时启动。一旦时间过去,我的意图是关闭程序;但是,我收到无效操作异常。我的程序的不同部分也使用 Close() 操作,但即使我从程序中删除它,它仍然会抛出错误。我怎样才能让它正常工作?

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

尝试使用 Application.Current.Shutdown() 而不是 Close()

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

此外请确保您的 Public Class Password 不在另一个线程中。

在这种情况下你可以使用:

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