Get Current URL in IE Using Visual Basic

后端 未结 2 1251
独厮守ぢ
独厮守ぢ 2020-12-06 13:18

I am working with the Internet Explorer object in Visual Basic. Is there a way to copy the current URL IE is displaying so I can paste it elsewhere with my clipboard?

2条回答
  •  时光说笑
    2020-12-06 13:31

    Damn! This reminds me of my vb6 days :)

    Ok here is what I have. If there are more than 1 IE windows then it will take the last active (Current) IE window else if there is only one window then it would take that.

    '~~> Set a reference to Microsoft Internet Controls
    
    '~~> The GetWindow function retrieves the handle of a window that has
    '~~> the specified relationship (Z order or owner) to the specified window.
    Private Declare Function GetWindow Lib "user32" (ByVal hwnd As Long, _
    ByVal wCmd As Long) As Long
    
    '~~> The GetForegroundWindow function returns the handle of the foreground
    '~~> window (the window with which the user is currently working).
    Private Declare Function GetForegroundWindow Lib "user32" () As Long
    
    Sub GetURL()
        Dim sw As SHDocVw.ShellWindows
        Dim objIE As SHDocVw.InternetExplorer
        Dim topHwnd As Long, nextHwnd As Long
        Dim sURL As String, hwnds As String
    
        Set sw = New SHDocVw.ShellWindows
    
        '~~> Check the number of IE Windows Opened
        '~~> If more than 1
        hwnds = "|"
        If sw.Count > 1 Then
            '~~> Create a string of hwnds of all IE windows
            For Each objIE In sw
                hwnds = hwnds & objIE.hwnd & "|"
            Next
    
            '~~> Get handle of handle of the foreground window
            nextHwnd = GetForegroundWindow
    
            '~~> Check for the 1st IE window after foreground window
            Do While nextHwnd > 0
                nextHwnd = GetWindow(nextHwnd, 2&)
                If InStr(hwnds, "|" & nextHwnd & "|") > 0 Then
                    topHwnd = nextHwnd
                    Exit Do
                End If
            Loop
    
            '~~> Get the URL from the relevant IE window
            For Each objIE In sw
                If objIE.hwnd = topHwnd Then
                    sURL = objIE.LocationURL
                    Exit For
                End If
            Next
        '~~> If only 1 was found
        Else
            For Each objIE In sw
                sURL = objIE.LocationURL
            Next
        End If
    
        Debug.Print sURL
    
        Set sw = Nothing: Set objIE = Nothing
    End Sub
    

    NOTE: I have not done any error handling. I am sure you can take care of that ;)

提交回复
热议问题