3

我使用一种搜索 UI 元素的方法:

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;
            }
        }

此方法由另一个等待元素直到它出现在桌面上的方法调用。

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);

            }
        }

问题是,当我调用最后一个函数时:

waittopuielm("测试");

即使找不到元素,它也总是返回 true,在这种情况下,我希望测试失败。任何建议都会受到欢迎。

4

1 回答 1

2

看起来您的waittopuielem方法返回 void - 您的意思是发布类似此版本的内容,它返回一个布尔值吗?

    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;
    }

除此之外,您的代码似乎对我来说按预期工作。

一个建议:在您的findtopuielm方法中,将桌面元素搜索中的 TreeScope 值从 TreeScope.Descendants 更改为 TreeScope.Children:

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

TreeScope.Descendants 执行的递归搜索可能比您想要的要多 - 将搜索桌面元素的所有子元素,以及这些元素的每个子元素(即按钮、编辑控件等)。

因此,在搜索相对常见的字符串时找到错误元素的机会很高,除非您将 NameProperty PropertyCondition 与 AndCondition 中的其他属性结合起来以缩小搜索范围。

于 2012-12-23T00:10:00.680 回答