Tobia
Tobia

Reputation: 9524

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.

Upvotes: 0

Views: 1230

Answers (1)

alxnull
alxnull

Reputation: 919

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
}

Upvotes: 2

Related Questions