Equivalent to a keypreview property in WPF

后端 未结 3 781
春和景丽
春和景丽 2021-01-02 16:35

I\'m pondering taking the plunge to WPF from WinForms for some of my apps, currently I\'m working on the combined barcode-reader/text-entry program (healthcare patient forms

3条回答
  •  萌比男神i
    2021-01-02 17:06

    Thanks got it working! Only problem was I'm coding in VB not C#, but the basic idea holds. Neat to create a label out of thin air and use it to insert yourself in the event stream.

    If someone else is interested of the same solution but in VB for WPF, here's my test program, it manages to toss all 'a' characters typed, no matter what control has the focus:

    Class MainWindow
    
        Dim WithEvents labelFromThinAir As Label
    
        Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
            AddHandler MainWindow.PreviewKeyDown, AddressOf labelFromThinAir_PreviewKeyDown
        End Sub
    
        Private Sub labelFromThinAir_PreviewKeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
            TextBox1.Text = e.Key    ' watch 'em coming
            If (44 = e.Key) Then e.Handled = True
        End Sub
    
    End Class
    

    P.S. This was my first post on stackoverflow, really a useful site. Perhaps I'll be able to answer some questions in here myself later on :-)

提交回复
热议问题