使用Microsoft UI Automation获取所有Firefox打开的URL

时间:2014-08-04 18:39:41

标签: .net vb.net firefox ui-automation microsoft-ui-automation

我正在尝试重新启动firefox标签中打开的所有网址。

这是我到目前为止所做的,代码获取了所有的firefox网址,是的,但是它还检索了每个打开文档中的所有网址,例如来自论坛的嵌入式youtube网址等等...我没兴趣。

我如何解决这个问题?。

并且在尝试在此处转换为String时,它会抛出“类型'的第一次机会异常的一些例外'System.InvalidOperationException'发生在Microsoft.VisualBasic.dll '中:

test.Add(TryCast(DirectCast(d.GetCurrentPattern(ValuePattern.Pattern), ValuePattern).Current.Value, String))

...但是,如果我可以“正确地”过滤“控件以检索正确的网址,我应该解决问题。

此代码的另一个问题是,UI自动化使我的Firefox进程无法通过Takbar进行,我无法在运行这些UI自动化指令后按下Firefox任务栏按钮以最大化/最小化窗口。

Imports System.Windows.Automation

Public Shared Function GetFirefoxUrls(process As Process) As List(Of String)

    If process Is Nothing Then
        Throw New ArgumentNullException("process")

    ElseIf process.MainWindowHandle = IntPtr.Zero Then
        Throw New ArgumentException("Invalid process.", "process")

    Else

        Dim element As AutomationElement =
            AutomationElement.FromHandle(process.MainWindowHandle)

        If element Is Nothing Then
            Return Nothing

        Else

            Dim docs As AutomationElementCollection =
                element.FindAll(TreeScope.Subtree,
                                New PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Document))

            If docs Is Nothing Then
                Return Nothing

            Else

                Dim test As New List(Of String)

                For Each d In docs
                    Try
                        test.Add(TryCast(DirectCast(d.GetCurrentPattern(ValuePattern.Pattern), ValuePattern).Current.Value, String))

                    Catch ex As Exception
                        Debug.WriteLine(ex.Message)
                    End Try
                Next

                Return test

            End If ' doc Is Nothing

        End If ' element Is Nothing

    End If ' process Is Nothing

End Function

用法:

Dim urls As List(Of String) =
    GetFirefoxUrls(Process.GetProcessesByName("Firefox").First)

1 个答案:

答案 0 :(得分:2)

使用Inspect工具(在Windows 7 SDK中),我看到所有Firefox标签的URL EditControls都有Name =“搜索或输入地址”。我不记得你可以根据元素的名称创建一个PropertyCondition(我不相信你可以)。但是当您遍历Document元素时,是否可以获取每个元素的Name属性并在将它们添加到列表之前与“搜索或输入地址”进行比较? - 即,在这行代码之前:

test.Add(TryCast(DirectCast(d.GetCurrentPattern(ValuePattern.Pattern), ValuePattern).Current.Value, String))

[编辑]哎呀请不要理会,说得太早了。 Name =“搜索或输入地址”EditControl只是导航工具栏父级中的一个控件...它包含当前选项卡的URL,而不是每个页面的URL。

计划B:您是否可以构建一个测试应用程序,该应用程序遍历整个文档并在Firefox测试会话中再次比较已知URL文本片段片段的ValueProperty值 - 字符串如“http://”?然后看看这些元素与其他包含URL的元素有什么共同的属性 - 可能是一个共同的父名称等等。

相关问题