5

I am using the Microsoft UI Automation and have some problems with it, one being that I want to know if an AutomationElement is still alive. More precisely I want to check if a window has been closed. I think this is the most common case for this kind of question and I tried different scenarios, ending up with a solution where I try to access different properties of the element and see if it throws an ElementNotAvailableException. I also stumbled upon a property called IsOffscreen, which seems to be very helpful in this case. But still, as I couldn't find too much about this on the net, I want to know if there is a better solution. I haven't been too happy with the framework these last days because it seems very unstable to me (especially in finding an AutomationElement). Maybe you could help me get a little more expertise in my implementation.

Thank you very much

Marcel

Marcel Bonzelet
  • 238
  • 2
  • 13
  • Just let it tell you, use the [WindowClosed event](https://msdn.microsoft.com/en-us/library/system.windows.automation.windowpattern.windowclosedevent%28v=vs.110%29.aspx) – Hans Passant May 12 '15 at 11:36
  • I made some bad experiences with events which is why I haven't tried this yet. I will give it another chance. :) – Marcel Bonzelet May 12 '15 at 11:49

2 Answers2

1

Before fetching AutomationElement, you may catch the ElementNotAvailableException

try 
{
  var info = automationElement.Current;
  var name = info.Name;
}
catch (ElementNotAvailableException) {}
Raye
  • 46
  • 4
1

I would wrap it in an extension:

public static bool Alive(this AutomationElement ae)
{
    try
    {
        var t = ae.Current.Name;
        return true;
    }
    catch(ElementNotAvailableException)
    {
        return false;
    }
}
null.pizza
  • 11
  • 1
  • 2