Как получить URL активной вкладки в браузере в VB.net - PullRequest
0 голосов
/ 25 октября 2018

Я нахожусь в процессе кодирования приложения для захвата URL активной вкладки в браузере Chrome.Я просмотрел некоторые коды, и все эти коды приводили к зависанию графического интерфейса и требовали много времени для получения 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 голосов
/ 04 ноября 2018

Наконец-то нашел ответ на мой вопрос,

Я заблокировал запросы, полученные из других приложений, и сосредоточился только на браузере 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
...