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

2019-04-01 02:02发布

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

5条回答
唯我独甜
2楼-- · 2019-04-01 02:16

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

查看更多
Bombasti
3楼-- · 2019-04-01 02:21

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

        }
    }
查看更多
闹够了就滚
4楼-- · 2019-04-01 02:27

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.

查看更多
我只想做你的唯一
5楼-- · 2019-04-01 02:34

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.

查看更多
趁早两清
6楼-- · 2019-04-01 02:39

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

查看更多
登录 后发表回答