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?
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.
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With