Search code examples
c#wpfeventskeyboardkeydown

How can I listen to keyboard events in all controls of a Window?


I have to listen to keyboard event in my Window, but if I use this code:

 MyWindow.KeyDown += new KeyEventHandler(MainWindow_KeyDown);

I don't get events fired inside other controls, like textbox. How can I get events from ALL controls and stop the propagation of the event to its original control?

EDIT

I tried this code:

EventManager.RegisterClassHandler(typeof(Window), Window.KeyDownEvent, new KeyEventHandler(MainWindow_KeyDown));

I works for most case, but for example it did not get the HOME key when I'm inside a textbox.


Solution

  • Have look into PreviewKeyDown:

    this.PreviewKeyDown += MainWindow_PreviewKeyDown;
    

    Event handler:

    private void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)
    {
         // do some stuff
         e.Handled = true // Stops propagating the event
    }