How can I set evenHandler in WPF for all windows (whole application)?
How do I set an event handler (for example keydown
) on the whole solution, not just one window?
Register a global event handler in your application class (App.cs), for example:
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 event KeyDown
for anyone Window
in your application. You can dump e
on KeyEventArgs
to get 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 must use a delegate to bind the event (wherever it is) and a function that you are ready to run when the event jumps.
you can load as many events as you like for your delegate.
MZE.
Well, KeyDown
will only work in the current window, because you need focus for KeyDown
. What you can do is add a handler to all windows and send another event to those handlers, and then register all the classes you need with this new event.
see the template Observer
You can not. The fighter logs the event in all windows and passes it to a global function / event or (in case of key change or similar) you use some kind of global "event binding" (like THIS for the keyboard).