In my case it worked by adding that code to the main window. However, I simplified it a bit:
public partial class MyMainWindow : Window
{
public MyMainWindow() {
GotFocus += WindowGotFocus;
}
private void WindowGotFocus(object sender, RoutedEventArgs e)
{
WindowInteropHelper helper = new WindowInteropHelper(this);
var mainWindowAutomationElement = AutomationElement.FromHandle(helper.Handle);
Automation.AddStructureChangedEventHandler(mainWindowAutomationElement, TreeScope.Element,
delegate {});
GotFocus -= WindowGotFocus;
}
}
The only problem with this approach, in my machine, is that the debugger window gets cluttered with messages like:
- A first chance exception of type System.Windows.Automation.ElementNotAvailableException' occurred in PresentationCore.dll
- A first chance exception of type 'System.ArgumentException' occurred in UIAutomationClientsideProviders.dll
- A first chance exception of type 'System.NotSupportedException' occurred in mscorlib.dll
- A first chance exception of type 'System.ComponentModel.Win32Exception' occurred in UIAutomationClient.dll
All happening many many times. I couldn't fix these messages, but my application is running faster now.