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

∥☆過路亽.° 提交于 2019-12-05 03:33:06

问题


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



来源:https://stackoverflow.com/questions/10027182/how-to-set-an-evenhandler-in-wpf-to-all-windows-entire-application

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