使用UI自动化获取Firefox URL

我试图使用以下代码在Firefox中获取URL的值。 问题是它只返回“搜索或输入地址”(参见下面的Inspect.exe树结构)。 看起来我需要降低一级。 有人可以告诉我如何做到这一点。

public static string GetFirefoxUrl(IntPtr pointer) { AutomationElement element = AutomationElement.FromHandle(pointer); if (element == null) return null; AutomationElement tsbCtrl = element.FindFirst(TreeScope.Subtree, new PropertyCondition(AutomationElement.NameProperty, "Search or enter address")); return ((ValuePattern)tsbCtrl.GetCurrentPattern(ValuePattern.Pattern)).Current.Value as string; } 

对于树结构,请参阅:

在此处输入图像描述

目前尚不清楚您从哪个元素开始搜索,但是您有两个具有该名称的元素。 一个是combobox控件,另一个是编辑控件。 尝试使用AndCondition组合多个PropertyCondition对象:

 var nameCondition = new PropertyCondition(AutomationElement.NameProperty, "Search or enter address"); var controlCondition = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit); var condition = new AndCondition(nameCondition, controlCondition); AutomationElement editBox = element.FindFirst(TreeScope.Subtree, condition); // use ValuePattern to get the value 

如果从combobox开始搜索,则可以将TreeScope.Subtree更改为TreeScope.Descendants因为Subtree包含搜索中的当前元素。