Equivalent to a keypreview property in WPF

后端 未结 3 741
春和景丽
春和景丽 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条回答
  • 2021-01-02 17:05

    use the override in your own UserControls or Controls (this is an override from UIElement)

    protected override void OnPreviewKeyDown(System.Windows.Input.KeyEventArgs e) {
         base.OnPreviewKeyDown(e);
      }
    

    if you want to preview the key down on any element which you dont create you can do this:

     Label label = new Label();
     label.PreviewKeyDown += new KeyEventHandler(label_PreviewKeyDown);
    

    and then have a handler like so :-

      void label_PreviewKeyDown(object sender, KeyEventArgs e) {
    
      }
    

    if you mark the event as handled (e.Handled = true;) this will stop the KeyDown event being raised.

    0 讨论(0)
  • 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 :-)

    0 讨论(0)
  • 2021-01-02 17:12

    WPF uses event bubbling and tunneling. In other words the events travel down and up the visual element tree. Some events will have a corresponding Preview event. So MouseDown will have a PreviewMouseDown that you can respond to. Check out this link and scroll down to the WPF Input Events section.

    0 讨论(0)
提交回复
热议问题