How to set an evenHandler in WPF to all windows (entire application)?

c#, event-handling, keydown, wpf

Solution

Register a global event handler in your application class (App.cs), like this:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        EventManager.RegisterClassHandler(typeof(Window), Window.KeyDownEvent, new RoutedEventHandler(Window_KeyDown));
    }

    void Window_KeyDown(object sender, RoutedEventArgs e)
    {
        // your code here
    }
}

This will handle the `KeyDown` event for any `Window` in your app. You can cast `e` to `KeyEventArgs` to get to the information about the pressed key.

Problem

How can I set an event handler (such as `keydown`) to entire solution, not a single window?

Original source