How to set an evenHandler in WPF to all windows (e

2019-04-01 01:54发布

问题:

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

回答1:

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.



回答2:

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) {

        }
    }


回答3:

You should use a delegate, to connect the event(wherever it is) and the function your willing to work when the event jumps.

you can load as many events as you want to your delegate.

mzE.



回答4:

Well, KeyDown will work only in the current window, because you need focus for KeyDown. What you can do is add a handler to all windows and dispatch another event in those handlers, then register all classes that you need with this new event.

alternatively, have a look at the Observer pattern



回答5:

You can't.
Eighter you register the event in all windows and pass it on to a global function/event or (in case of the keydown or similar) you use some global "event catching" (like THIS for the keyboard).