以下是一个示例VBA代码,通过窗口标题来捕获所有特定窗口的句柄:
Option Explicit
Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As LongPtr
Declare PtrSafe Function GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" (ByVal hwnd As LongPtr) As Long
Declare PtrSafe Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As LongPtr, ByVal lpString As String, ByVal cch As Long) As Long
Sub GetWindowHandlesByTitle()
Dim hwnd As LongPtr
Dim title As String
Dim handles As String
title = "特定窗口标题" ' 替换为需要捕获的窗口标题
hwnd = FindWindow(vbNullString, vbNullString) ' 获取第一个窗口的句柄
Do While hwnd <> 0
If GetWindowTextLength(hwnd) > 0 Then
Dim buffer As String
buffer = Space(GetWindowTextLength(hwnd) + 1)
GetWindowText hwnd, buffer, Len(buffer)
If InStr(buffer, title) > 0 Then
handles = handles & hwnd & vbCrLf
End If
End If
hwnd = FindWindowEx(0, hwnd, vbNullString, vbNullString) ' 获取下一个窗口的句柄
Loop
MsgBox "匹配窗口的句柄:" & vbCrLf & handles
End Sub
请注意替换title
变量的值为您要捕获的特定窗口的标题。该代码将通过遍历所有窗口的句柄,并将具有指定标题的窗口句柄保存在handles
变量中。最后,它将通过消息框显示匹配窗口的句柄。