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

最后都变了- 提交于 2019-12-03 17:08:29

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.

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

        }
    }

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.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!