Question

I use a method that searches an UI element:

public static bool findtopuielm(string uiitemname)
        {
            bool res = false;
            try
            {
                AutomationElement desktopelem = AutomationElement.RootElement;
                if (desktopelem != null)
                {
                    Condition condition = new PropertyCondition(AutomationElement.NameProperty, uiitemname);
                    AutomationElement appElement = desktopelem.FindFirst(TreeScope.Descendants, condition);
                    if (appElement != null)
                    {
                        res = true;
                    }

                }
                return res;
            }
            catch (Win32Exception)
            {
                // To do: error handling
                return false;
            }
        }

This method is called by another one that waits an element until it appears on desktop.

public static void waittopuielm(string appname, int retries = 1000, int retrytimeout = 1000)
        {
        for (int i = 1; i <= retries; i++)
        {
            if (findtopuielm(appname))

                break;
                Thread.Sleep(retrytimeout);

            }
        }

The thing is that when I call the last function for example:

waittopuielm("Test");

It always returns true even if the element is not found, in that case I want the test to fail. Any suggestion would be welcomed.

Was it helpful?

Solution

It looks like your waittopuielem method returns void - did you mean to post something like this version, which returns a bool?

    public static bool waittopuielm(string appname, int retries = 1000, int retrytimeout = 1000)
    {
        bool foundMatch = false;
        for (int i = 1; i <= retries; i++)
        {
            if (findtopuielm(appname))
            {
                foundMatch = true;
                break;
            }
            else
            {
                Console.WriteLine("No match found, sleeping...");
            }
            Thread.Sleep(retrytimeout);
        }
        return foundMatch;
    }

Other than that, your code seems to work as expected for me.

One suggestion: In your findtopuielm method, change the TreeScope value in the desktop element search from TreeScope.Descendants to TreeScope.Children:

AutomationElement appElement = desktopelem.FindFirst(TreeScope.Children, condition);

TreeScope.Descendants is probably doing more recursive searching than you want - all children of the desktop element will be searched, as well as every child of those elements (i.e. buttons, edit controls, and so forth).

So, the chances of finding the wrong element when searching for a relatively common string are high, unless you combine your NameProperty PropertyCondition with other properties in an AndCondition to narrow your search.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top