Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 930
Programer Avatar asked Apr 05 '12 10:04

Programer


2 Answers

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.

like image 51
Matt Hamilton Avatar answered Sep 17 '22 23:09

Matt Hamilton


How about this:

 public partial class App : Application {
        protected override void OnStartup(StartupEventArgs e) {
            EventManager.RegisterClassHandler(typeof(Window), Window.KeyDownEvent, new RoutedEventHandler(KeyDown));
            base.OnStartup(e);
        }

        void KeyDown(object sender, RoutedEventArgs e) {

        }
    }
like image 39
ionden Avatar answered Sep 20 '22 23:09

ionden