Friday, March 16, 2007

Global Events Hooking

WPF has really great engines for global hooking. Dependency Properties/Objects are only small part of those engines. Today, we'll look into Routed Events and EventManager

Let's take a scenario, where I want to handle OnClosing event of all windows in my application. The propose is clear - popup an exclamation asking me to approve this action.

The "legacy" way is to create kind of BaseWindow, derived from Window Class and override onClosing event to popup my message. This approach means, that I have to inherit BaseWindow in all windows or instead of creation of Window instance, create Basewindow one.

But, I want to do it easily, and I'm in WPF world, so let's start new WPF project and put into App.xaml.cs class following lines


protected override void OnStartup(StartupEventArgs e)
            EventManager.RegisterClassHandler(typeof(Window), Window.LoadedEvent, new RoutedEventHandler(WindowLoaded));

Done. Now let's understand what we did. We register globally routed event Window.Loaded for each new instance of Window class, so each time this event will be fired (that not mention, if we have or will have an instance of window), EventManager will subscribe to it and execute WindowLoaded method. The rest is really simple. Let's implement WindowLoaded and subscribe the loaded instance to our message popping


void WindowLoaded(object sender, RoutedEventArgs e)
            Window w = sender as Window;
            if (w != null)
                w.Closing += new System.ComponentModel.CancelEventHandler(w_Closing);
void w_Closing(object sender, System.ComponentModel.CancelEventArgs e)
            if (MessageBox.Show("Really [with EventManager]?", "Workaround window", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.No)
                e.Cancel = true;

That's all, folks. Now each window (or window derived class) in my system, even those how I do not know will ask me about closing each time, I'll try to close them.

Nice, don't you think?

No comments: