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));
 
            base.OnStartup(e);
        }

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?

  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DotNetKicks
  • DZone
  • Live
  • Reddit
  • TwitThis
  • email
  • Slashdot
  • StumbleUpon

3 Responses to “Global Events Hooking”

  1. Daniel Says:

    How to make the same with Popup or ComboBox? Popup.Opened is not a routed event. And Loaded does not work

  2. Just code - Tamir Khason Says:

    Today, we’ll speak about RoutedEvent and possible memory leaks associated with them. If you ever use

  3. Just code - Tamir Khason Says:

    What’s this post about? This post begins with DIY. Try to do the following: Add simple ListView to your

Leave a Reply

Recommended

 


Sponsor


Partners

WPF Disciples
Dreamhost
Code Project
Switched to Better Place

Together