Trucos Obtener una lista jerárquica de nombres de ventana y clases

INTRODUCCION

Para determinar si una ventana "hija" (child window) de una aplicación está abierta necesitamos saber si una ventana es hija de la aplicación principal, "nieta" (grandchild) o es una ventana independiente. Este artículo muestra un método para crear una lista jerárquica de todas las ventanas abiertas y de sus nombres de clase, haciendo más fácil la navegación por la jerarquía de ventanas de un programa.


EJEMPLO

 1.Creamos un nuevo proyecto con un formulario y un módulo.

 2.Añadimos los siguientes controles:

      Control Nombre Propiedad Valor
      ------------------------------------------------
      Command button Command1
      Text box Text1 MultiLine TRUE
      Text box Text1 Scrollbars 2- Vertical

 3.Escribimos el siguiente código en el módulo :

      Option Explicit
      Public Const GW_CHILD = 5
      Public Const GW_HWNDNEXT = 2
      Declare Function GetWindow Lib "user32" (ByVal hwnd As Long, ByVal wCmd As Long) As Long
      Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
      Declare Function GetTopWindow Lib "user32" (ByVal hwnd As Long) As Long
      Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hwnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long

 4.Añadimos el siguiente código en el formulario:

      Sub AddChildWindows(ByVal hwndParent As Long, ByVal Level As Long)
      Dim WT As String, CN As String, Length As Long, hwnd As Long
      If Level = 0 Then
         hwnd = hwndParent
      Else
         hwnd = GetWindow(hwndParent, GW_CHILD)
      End If
      Do While hwnd <> 0
         WT = Space(256)
         Length = GetWindowText(hwnd, WT, 255)
         WT = Left$(WT, Length)
         CN = Space(256)
         Length = GetClassName(hwnd, CN, 255)
         CN = Left$(CN, Length)
         Me!Text1 = Me!Text1 & vbCrLf & String(2 * Level, ".") & WT & " (" & CN & ")"
         AddChildWindows hwnd, Level + 1
         hwnd = GetWindow(hwnd, GW_HWNDNEXT)
      Loop
      End Sub

      Sub Command1_Click()
      Dim hwnd As Long
      hwnd = GetTopWindow(0)
      If hwnd <> 0 Then
         AddChildWindows hwnd, 0
      End If
      End Sub


 5.Ejecutamos el proyexto

 6.Presionamos el CommandButton. El textbox se llenará on una lista de ventanas y sus hijas ordenadas jerárquicamente. El nombre de clase seguirá al de la ventana :

      MainWindowName (WindowClass)
      ..ChildWindowName (WindowClass)
      ....GrandchildWindowName (WindowClass)


NOTE: No todas las ventanas tendrán nombre pero todas tendrán nombre de clase.



Trucos Trucos

Visual Basic Página de Visual Basic

Página principal Página principal

www.jrubi.com