Equivalent to a keypreview property in WPF

Henry Skoglund picture Henry Skoglund · Dec 17, 2009 · Viewed 8.7k times · Source

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

Answer

Aran Mulholland picture Aran Mulholland · Dec 17, 2009

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.