如何用Windows api查找标题相似的所有窗口句柄VB6

作者 : admin 本文共1835个字,预计阅读时间需要5分钟 发布时间: 2024-06-15 共1人阅读

在 VB6 中,可以使用 FindWindow API 函数来查找窗口句柄。这个函数接受两个参数,一个是窗口类名,另一个是窗口标题。如果你只知道窗口标题的一部分或者想查找标题相似的所有窗口,可以使用通配符来进行模糊匹配。

在 VB6 中,FindWindow API 函数的原型如下:

Declare Function FindWindow Lib "user32" Alias "FindWindowA" ( _
    ByVal lpClassName As String, _
    ByVal lpWindowName As String _
) As Long

可以使用下面的函数来查找标题相似的所有窗口句柄:

Declare Function FindWindow Lib "user32" Alias "FindWindowA" ( _
    ByVal lpClassName As String, _
    ByVal lpWindowName As String _
) As Long

Declare Function EnumWindows Lib "user32" ( _
    ByVal lpEnumFunc As Long, _
    ByVal lParam 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 GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" ( _
    ByVal hwnd As Long _
) As Long

Function FindSimilarWindows( _
    ByVal strPattern As String _
) As Collection
    Dim hwnd As Long
    Dim strWindowTitle As String
    Dim lngWindowTitleLength As Long
    Dim lngResult As Long
    Dim colWindows As New Collection
    Dim lngEnumFunc As Long
    
    ' 创建枚举窗口函数的回调函数
    lngEnumFunc = AddressOf EnumWindowsProc
    
    ' 枚举所有窗口
    lngResult = EnumWindows(lngEnumFunc, 0&)
    
    If lngResult  0 Then
        MsgBox "枚举窗口失败!"
        Exit Function
    End If
    
    ' 查找标题相似的窗口
    Function EnumWindowsProc( _
        ByVal hwnd As Long, _
        ByVal lParam As Long _
    ) As Long
        Dim strWindowTitle As String
        Dim lngWindowTitleLength As Long
        
        ' 获取窗口标题长度
        lngWindowTitleLength = GetWindowTextLength(hwnd)
        If lngWindowTitleLength = 0 Then Exit Function
        
        ' 分配缓冲区
        strWindowTitle = String$(lngWindowTitleLength, vbNullChar)
        
        ' 获取窗口标题
        If GetWindowText(hwnd, strWindowTitle, lngWindowTitleLength + 1) Then
            ' 使用 Like 运算符进行模糊匹配
            If strWindowTitle Like strPattern Then
                colWindows.Add hwnd, CStr(hwnd)
            End If
        End If
        
        ' 继续枚举下一个窗口
        EnumWindowsProc = 1
    End Function
    
    Set FindSimilarWindows = colWindows
End Function

使用方法:

Dim colWindows As Collection
Dim hwnd As Variant
Dim i As Long

' 查找标题中包含 "Msgbox" 的所有窗口
Set colWindows = FindSimilarWindows("*Msgbox*")

' 输出所有找到的窗口句柄
For i = 1 To colWindows.Count
    hwnd = colWindows.Item(i)
    Debug.Print hwnd
Next

需要注意的是,上面的代码使用了 API 函数,因此在使用前需要添加相应的引用和声明。同时,由于 API 函数的使用可能会导致系统不稳定,因此请谨慎使用。

本站无任何商业行为
个人在线分享 » 如何用Windows api查找标题相似的所有窗口句柄VB6
E-->