如何在VB.net中的浏览器中获取活动选项卡的URL

时间:2018-10-25 10:53:11

标签: vb.net google-chrome url ui-automation freeze

我正在将应用程序编码为Chrome浏览器中的活动标签页的捕获网址。我经历了一些代码,所有这些代码都导致GUI冻结,并且花费很长时间才能获得URL。我真正想要的是获取活动选项卡的URL。仅此而已,这就是我所使用的。非常感谢您的帮助。

Imports System.Windows.Automation

Public Class Form1
    Private Const ChromeProcess As [String] = "chrome"
    Private Const AddressCtl As [String] = "Address and search bar"
Public Function GetChromeActiveWindowUrl() As [String]
    Dim procs = Process.GetProcessesByName(ChromeProcess)

    If (procs.Length = 0) Then
        Return [String].Empty
    End If

    Return procs _
.Where(Function(p) p.MainWindowHandle <> IntPtr.Zero) _
.Select(Function(s) GetUrlControl(s)) _
.Where(Function(p) p IsNot Nothing) _
.Select(Function(s) GetValuePattern(s)) _
.Where(Function(p) p.Item2.Length > 0) _
.Select(Function(s) GetValuePatternUrl(s)) _
.FirstOrDefault

End Function

Private Function GetUrlControl(
proses As Process) _
As AutomationElement

    Dim propCondition =
    New PropertyCondition(
    AutomationElement.NameProperty,
    AddressCtl)
    Return AutomationElement _
    .FromHandle(proses.MainWindowHandle) _
    .FindFirst(
        TreeScope.Descendants,
        propCondition)

End Function

Private Function GetValuePatternUrl(
element As Tuple(Of
AutomationElement, AutomationPattern())) As [String]

    Dim ap = element.Item2(0)
    Dim ovp = element.Item1.GetCurrentPattern(ap)
    Dim vp = CType(ovp, ValuePattern)

    Return vp.Current.Value
End Function



Private Function GetValuePattern(
element As AutomationElement) _

作为元组(的           AutomationElement,           AutomationPattern())

      Return New Tuple(Of
      AutomationElement,
      AutomationPattern())(
      element,
      element.GetSupportedPatterns())
End Function

1 个答案:

答案 0 :(得分:0)

最终找到了我的问题的答案,

我已阻止从其他应用程序接收到的请求,并且只专注于chrome浏览器

Dim hWnd As IntPtr = GetForegroundWindow()
Dim ProcessID As UInt32 = Nothing
GetWindowThreadProcessId(hWnd, ProcessID)
Dim Proc As Process = Process.GetProcessById(ProcessID)
str_application_category = Proc.MainModule.FileVersionInfo.ProductName

If str_application_category = "Google Chrome" Then
str_application_path = GetChromeActiveWindowUrl()
End If

Catch ex As Exception

End Try