How can I set an event handler (such as keydown
) to entire solution, not a single window?
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).
来源:https://stackoverflow.com/questions/10027182/how-to-set-an-evenhandler-in-wpf-to-all-windows-entire-application