Capturing WPF UserControl Key Events When Hosted In A WinForms ElementHost Control


I have had a very difficult problem that took nearly all day to solve. The problem was that I had a Windows Forms application with an ElementHost control for hosting WPF UserControls. I could quite easily manipulate the user controls with the mouse, because they are specifically designed to be used with the mouse. However, I became unstuck when I tried to implement abandoning the user controls via the F4 key press. No matter what I tried, I could not get any KeyPress, KeyDown, PreviewKeyPress, or PreviewKeyDown events to work. I tried various methods suggested by Microsoft and various forums. But to my dismay, none of these worked. Fortunately, after much banging my head against the wall I found a solution that worked.

The solution to the problem described above is to:

  1. Set the Focusable property of the WPF UserControl to true;
  2. In the WPF UserControl’s Loaded event, set the focus to the WPF UserControl;
  3. Finally, capture the WPF UserControl’s PreviewKeyDown event.

The solution works really well, and appears to fire consistently regardless of what I do on the WPF UserControl. If you face the same issue, then I hope this works for you.

Advertisements

One thought on “Capturing WPF UserControl Key Events When Hosted In A WinForms ElementHost Control

Comments are closed.