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 :)
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
}
}
}