开发者

Equivalent to a keypreview property in WPF

开发者 https://www.devze.com 2022-12-14 09:45 出处:网络
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).

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).

To be able to process the barcode characters, I rely on the Keypreview property in WinForms (because barcodes can be scanned regardless of what control has the focus).

But I canno开发者_C百科t seem to find a KeyPreview property in neither VS2008 or VS2010, for a WPF app.

Is there an alternative approach/solution to handle my barcode characters in WPF?

Rgrds Henry


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.


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 :-)


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

精彩评论

暂无评论...
验证码 换一张
取 消