如何在vba中用api回调函数EnumChildProc遍历某个窗口的所有子窗口?

在前面,我们介绍了如何在vba中用api回调函数EnumWindowsProc遍历顶层窗口

本文我们将介绍如何遍历某个窗口的所有子窗口。

使用API函数EnumChildWindows可以将某个窗口的所有子窗口的句柄依次轮流传递给回调函数EnumChildProc。原理同EnumWindows,这里不再详细介绍。

以下是获取excel应用程序的所有子窗口的代码

Public Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hwnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Public Declare Function EnumWindows Lib "user32" (ByVal lpEnumFunc As Long, ByVal lParam As Long) As Long
Public Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Public Declare Function EnumChildWindows Lib "user32" (ByVal hWndParent As Long, ByVal lpEnumFunc As Long, ByVal lParam As Long) As Long
Public Function EnumChildProc(ByVal hwnd As Long, ByVal lParam As Long) As Boolean
    Dim oWK As Worksheet
    Set oWK = ActiveSheet
    '定义一个变量存储类名
    Dim sCN As String
    '定义一个变量存储窗口的标题名字
    Dim sTitle As String
    '先填充空格
    sCN = Space(255)
    sTitle = Space(1024)
    Dim iLen1, iLen2
    '获得实际的类名字符长度
    iLen1 = GetClassName(hwnd, sCN, 256)
    iLen2 = GetWindowText(hwnd, sTitle, 1025)
    '提取实际的类名
    sCN = Left(sCN, iLen1)
    sTitle = Left(sTitle, iLen2)
    With oWK
        .Range("a1:B1") = Array("类名", "标题")
        iRow = .Range("a65536").End(xlUp).Row + 1
        .Cells(iRow, 1) = sCN
        .Cells(iRow, 2) = sTitle
    End With
    '继续调用
   EnumChildProc = True
End Function
Sub QQ1722187970()
    Dim oWK As Worksheet
    Set oWK = ActiveSheet
    oWK.Cells.Clear
    '开始遍历
     EnumChildWindows Excel.Application.hwnd, AddressOf EnumChildProc, 0
End Sub

 

       

发表评论