2012-06-22 49 views
6

Estoy trabajando con el objeto de Internet Explorer en Visual Basic. ¿Hay alguna manera de copiar la URL actual que IE muestra para poder pegarla en otro lugar con mi portapapeles?Obtener URL actual en IE con Visual Basic

+0

Esto quizás sea un poco más complejo de lo que usted desea, y es VB.NET, pero debe ser traducible. Espero que ayude [Obtener URL] (http://www.codeproject.com/Articles/204929/Getting-current-browser-URL-with-VB-NET) –

+0

¿Qué aplicación? Excel, Access ...? – Fionnuala

+0

¿Cómo se ha conectado con el IE actual? Esto es importante, ya que si hay más de 1 ventana de IE abierta. ¿Eres vinculante con IE según el título? Mostrarnos más código realmente ayudaría. Si desea que el código obtenga la URL de todas las ventanas de IE, entonces puede establecer una referencia a Microsoft Internet Controls y luego puede recorrer todas las ventanas de IE usando 'ShellWindows'. Una vez que obtenga la ventana, simplemente use '.LocationURL' para obtener la dirección. –

Respuesta

6

Suponiendo que ya haya identificado la ventana de IE, que en sí es un poco más complicado - puedo más detalles sobre esto, si es necesario:

Dim ieIEWindow As SHDocVw.InternetExplorer 
Dim sIEURL As String 

'Set your IE Window 

sIEURL = ieIEWindow.LocationURL 

Para obtener la ventana de IE, tendrá que hacer referencia a la biblioteca Microsoft Internet Controls (ieframe.dll) en el editor de VBA yendo a Tools =>References... y seleccionándolo de la lista. Si ese artículo no está disponible, el archivo .dll para mí se encuentra en C:\Windows\System32\ieframe.dll.

Una vez que se establece la referencia, tendrá acceso a la biblioteca llamada SHDocVw en su código.

se puede agarrar la ventana de IE (suponiendo único abierto) utilizando la siguiente (no probado, modificado/reducida de mi propio código de trabajo):

Public Function GrabIEWindow() As SHDocView.InternetExplorer 

Dim swShellWindows As New SHDocVw.ShellWindows 
Dim ieOpenIEWindow As SHDocVw.InternetExplorer 

    Set GrabIEWindow = Nothing 

    ' Look at the URLs of any active Explorer windows 
    ' (this includes WINDOWS windows, not just IE) 
    For Each ieOpenIEWindow In objShellWindows 

     ' Check the I.E. window to see if it's pointed 
     ' to a web location (http) 
     If Left$(ieOpenIEWindow.LocationURL, 4) = "http" Then 
      ' If so, set this window as the one to use. 
      ' This will need to be modified to create 
      ' a list if you want to select from more 
      ' than one open window 

      ' Optional grab the HWND for later reference... 
      Dim lWindowID As Long 
      lWindowID = ieOpenIEWindow.HWND 

      Set GrabIEWindow = ieOpenIEWindow 

      Exit Function 
     End If 

    Next OpenIEWindow 

End Function 

Lo anterior puede también ser modificado para permitir una selección de múltiples ventanas abiertas de IE.

+0

+ 1 SÍ Si solo hay una ventana abierta o si se identifica la ventana IE. –

+0

@SiddharthRout Utilizo este tipo de automatización a diario y he desarrollado algunas herramientas sucias pero efectivas para lograr esto. (formulario que enumera todas las ventanas disponibles, el usuario selecciona, luego la sesión se une al HWND, en algunos casos asegura que la ventana aún está abierta, etc.) – Gaffi

+0

Kool :) Es posible que desee modificar su publicación y agregar que el usuario necesita agregar referencia a Microsoft Internet Controls? –

2

¡Maldición! Esto me recuerda a mi vb6 días :)

Ok aquí es lo que tengo. Si hay más de 1 ventana IE, entonces tomará la última ventana activa (Actual) IE, de lo contrario, si solo hay una ventana, se necesitaría eso.

'~~> 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 

NOTA: No he hecho ninguna gestión de errores. Estoy seguro de que puede encargarse de eso;)

+0

¡Esto es bastante diferente de mis métodos! Utilizo algunas de las referencias dll externas, pero solo para manipular las páginas (es decir, saltar hacia adelante y hacia atrás entre múltiples). ¿Cómo se maneja 'sw.Count = 1' cuando la única ventana tiene una ruta que no es http, ya que una ventana puede ser un marco estándar de Windows (es decir,' My Computer')? – Gaffi

+0

Como mencioné, no he incluido ningún manejo de errores. usando 'Left $ (ieOpenIEWindow.LocationURL, 4) = "http" 'como lo has hecho hubiera sido mi siguiente paso, pero estaba probando con 3 ventanas IE válidas con direcciones reales. :) Pruébalo con más de 1 ventana de IE y mira qué URL obtienes? –