0

I'm working on a small app that uses UI Automation and sits atop a third party app to intercept certain events and inject and extract values into/from input fields. The other app seems to be using a ContentControl in WPF to show all the different screens, within one single Window. All of my code seems to be working well, IF the control it's expecting exists already. At this point I'm trying to tie everything together by adding the button click automation handlers when the button has been created, but I'm not sure the best way to do it.

I can currently capture button click events within the external app, if I call this code when the button has been created:

var cond = new PropertyCondition(AutomationElement.NameProperty, "SearchButton");
var searchButtonElement = _rootWindowElement?.FindFirst(TreeScope.Descendants, cond);
Automation.AddAutomationEventHandler(InvokePattern.InvokedEvent, searchButtonElement, TreeScope.Element, ((o, args) =>
{
    MessageBox.Show("Hello World");
}));

Everything works well if that screen is already up and showing that button, but if it hasn't been instantiated yet, searchButtonElement is null. What's the best way for me to wait for the button "SearchButton" to become instantiated and valid so I can attach my automation invoke handler to it?

Also, what would be the best way to detach my handler when it's no longer available (... is that even necessary)?

Basically, the external app starts up on a main menu screen, once the "Show search screen" button is clicked, I need to run code when the next screen's "Search" button is clicked.

Thanks

Adam Plocher
  • 13,994
  • 6
  • 46
  • 79
  • Since the client is in another app, you could just do a while{sleep()} until the button appears – Simon Mourier Jul 28 '15 at 09:30
  • Thanks Simon, that is something I considered, but isn't trying to check for the control's existence fairly expensive (of course that may be true with an event handler, too)? It would also leave a possibility (although small - depending on the sleep duration) that the Search button could be clicked without registering the intercepting handler. I may end up having to go that route, I was just hoping there would be something cleaner. I did mess with `AutomationElement.StructureChangedEvent` but there are few examples on the web and it seemed unreliable. – Adam Plocher Jul 28 '15 at 09:35
  • Well, that route has worked fine for me :-) Of course, it's better to add a timeout check so you make sure you don't hang indefinitely, also make sure you carefully choose the TreeScope. I never use recursive searches. – Simon Mourier Jul 28 '15 at 09:53
  • You could add a structure changed event handler on the element that is sure to be present (the content control?) and in that handler install your invoked event handler – o_weisman Sep 06 '15 at 11:37

0 Answers0