Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent to a keypreview property in WPF

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 cannot 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

like image 895
Henry Skoglund Avatar asked Dec 16 '09 23:12

Henry Skoglund


People also ask

What is KeyPreview in c#?

Gets or sets a value indicating whether the form will receive key events before the event is passed to the control that has focus. public: property bool KeyPreview { bool get(); void set(bool value); }; C# Copy.

What is KeyPreview in vb net?

Use the KeyPreview property to specify whether the form-level keyboard event procedures are invoked before a control's keyboard event procedures. Read/write Boolean.


2 Answers

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.

like image 174
Aran Mulholland Avatar answered Sep 23 '22 20:09

Aran Mulholland


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

like image 26
Henry Skoglund Avatar answered Sep 21 '22 20:09

Henry Skoglund