Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I capture KeyDown event on a WPF Page or UserControl object?

Tags:

wpf

keydown

I have a Page with a UserControl on it. If the user presses Esc while anywhere on Page I want to handle.

I thought this would be as easy as hooking up the PreviewKeyDown event, testing for the Esc key, and then handling it. However, when I placed I breakpoint in the event handler I found it was never getting called. I thought perhaps the UserControl might be getting hit, so I tried PreviewKeyDown there... same result.

Does anyone know the proper place to test for a KeyDown or PreviewKeyDown on a Page object?

like image 639
Sailing Judo Avatar asked Dec 07 '08 16:12

Sailing Judo


People also ask

What is the use of on KeyDown event?

Definition and Usage The onkeydown event occurs when the user is pressing a key (on the keyboard). Tip: The order of events related to the onkeydown event: onkeydown. onkeypress.

What is KeyDown event in Visual Basic?

KeyDown event: The KeyDown event occurred when a user presses a key on the keyboard. It repeats while the user keeps the key depressed. The KeyDown event is provided by the Keyboard event in the VB.NET application. KeyUp event: The KeyUp event is rising when a user releases a key on the keyboard.

What is KeyDown event in Javascript?

The keydown event is fired when a key is pressed. Unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.


1 Answers

Attach to the Window's Event

After the control is loaded, attach to the Window's KeyDown event (or any event) by using Window.GetWindow(this), like so:

The XAML

<UserControl Loaded="UserControl_Loaded"> </UserControl> 

The Code Behind

private void UserControl_Loaded(object sender, RoutedEventArgs e) {   var window = Window.GetWindow(this);   window.KeyDown += HandleKeyPress; }  private void HandleKeyPress(object sender, KeyEventArgs e) {   //Do work } 
like image 194
Daniel Avatar answered Sep 21 '22 20:09

Daniel