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

在 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 函数的使用可能会导致系统不稳定,因此请谨慎使用。

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

专注VB编程开发20年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值