1

I've had stumbled looking around for answers of how to create a global event that would be fired whenever a child window is being showed by another parent window. I want to have a event handler that would be use by all of this child windows without attaching it(the event handler) to every child window.

Is this even possible in WPF? If this possible any help would be appreciated thanks :)

Allan Chua
  • 9,305
  • 9
  • 41
  • 61

1 Answers1

2

It is unpossible to handle the Window.Loaded event in a "global" manner because it's routing type is "direct". Direct routed events do not follow a route, they are only handled within the same element on which they are raised. Hovewer you can use the following trick to handle any window creation in your application:

    // Main window initialization code 
    _argsField = typeof(DispatcherOperation).GetField("_args",
        BindingFlags.NonPublic | BindingFlags.Instance);

    Dispatcher.Hooks.OperationCompleted += Hooks_OperationCompleted;
}
FieldInfo _argsField;
void Hooks_OperationCompleted(object sender, DispatcherHookEventArgs e) {
    if(e.Operation.Priority == System.Windows.Threading.DispatcherPriority.Loaded) {
        var source = _argsField.GetValue(e.Operation) as System.Windows.Interop.HwndSource;
        if(source != null) {
            Window w = source.RootVisual as Window;
            // ... here you can operate with newly created window
        }
    }
}
DmitryG
  • 17,677
  • 1
  • 30
  • 53
  • Hi @DmitryG, Thanks for the letting me know that its was a direct event handler. Can i know what was the logic behind this code? thanks :) – Allan Chua May 05 '12 at 12:02
  • @AllanChua: There is simple logic: each Window created and shown in your application will be notified with Load event. This event will be delivered asynchronously via dispatcher operation. My code hooks this operation completion, thus it is possible to react on Window.Loaded just after this event will be processed. I've used reflection to get access to private information about the Window that was created... – DmitryG May 05 '12 at 15:05