我使用 Windows API 和 Excel VBA 来处理特定窗口,使用 FindWindow()
函数,但 FindWindow()
需要完整的标题/说明要查找的窗口的位置。
问题1
P_Win = FindWindow(vbNullString, "PlusApi_Excel Sample_17_39_12 Api 生成的订单")
在我的例子中,窗口将更改名称(动态)(窗口名称的某些部分将是固定的,而某些部分将是动态的)
例如。第一次窗口名称为“PlusApi_Excel Sample_17_39_12 Api generated Orders”
第二次将是“PlusApi_Excel Sample_17_45_13 Api generated Orders”
我想我需要用部件名称调用窗口,但我不知道该怎么做,请帮助我
问题2
上述挑战中,我还有一个问题,PlusApi 将被隐藏,但我的代码仍然显示正值。
我想我只需要调用“visible”
窗口。
最佳答案
我在 this vbforums.com answer 中找到了以下代码并增强它来查找可见或不可见窗口,因此希望能回答您的两个问题:
Option Explicit
Private Declare Function FindWindow Lib "User32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function GetWindowText Lib "User32" Alias "GetWindowTextA" (ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare Function GetWindowTextLength Lib "User32" Alias "GetWindowTextLengthA" (ByVal hWnd As Long) As Long
Private Declare Function GetWindow Lib "User32" (ByVal hWnd As Long, ByVal wCmd As Long) As Long
Private Declare Function IsWindowVisible Lib "User32" (ByVal hWnd As Long) As Boolean
Private Const GW_HWNDNEXT = 2
Private Sub Test()
Dim lhWndP As Long
If GetHandleFromPartialCaption(lhWndP, "Excel") = True Then
If IsWindowVisible(lhWndP) = True Then
MsgBox "Found VISIBLE Window Handle: " & lhWndP, vbOKOnly + vbInformation
Else
MsgBox "Found INVISIBLE Window Handle: " & lhWndP, vbOKOnly + vbInformation
End If
Else
MsgBox "Window 'Excel' not found!", vbOKOnly + vbExclamation
End If
End Sub
Private Function GetHandleFromPartialCaption(ByRef lWnd As Long, ByVal sCaption As String) As Boolean
Dim lhWndP As Long
Dim sStr As String
GetHandleFromPartialCaption = False
lhWndP = FindWindow(vbNullString, vbNullString) 'PARENT WINDOW
Do While lhWndP <> 0
sStr = String(GetWindowTextLength(lhWndP) + 1, Chr$(0))
GetWindowText lhWndP, sStr, Len(sStr)
sStr = Left$(sStr, Len(sStr) - 1)
If InStr(1, sStr, sCaption) > 0 Then
GetHandleFromPartialCaption = True
lWnd = lhWndP
Exit Do
End If
lhWndP = GetWindow(lhWndP, GW_HWNDNEXT)
Loop
End Function
该代码搜索部分标题为“Excel”的窗口,并告诉您是否找到它以及它是否是可见窗口。您应该能够根据自己的目的对其进行调整。
关于excel - 如何在 VBA 中使用 FindWindow 查找具有部分名称的可见或不可见窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25098263/