如何使用FindWindow在VBA中查找具有部分名称的可见或不可见窗口

Aru*_*C M 7 excel vba

我正在使用带有Excel VBA的Windows API来使用该FindWindow()功能处理特定窗口,但FindWindow()需要查找窗口的完整标题/标题.

问题1

P_Win = FindWindow(vbNullString, "PlusApi_Excel Sample_17_39_12 Api Generated Orders") 在我的情况下,窗口将更改名称(动态)(窗口名称的某些部分将被修复,某些部分将是动态的)

防爆.窗口名称是第一次"PlusApi_Excel Sample_17_39_12 Api Generated Orders" ,第二次,"PlusApi_Excel Sample_17_45_13 Api Generated Orders" 我认为我需要调用带有部件名称的窗口,但我不知道该怎么办,请帮助我

问题2

以上挑战我还有一个问题,即PlusApi将被隐藏,但我的代码仍显示正值.

我想我"visible"只需要打电话给窗口.

dji*_*kay 10

我在这个vbforums.com回答中找到了以下代码并对其进行了增强,以便查找可见或不可见的窗口,因此希望能够回答您的两个问题:

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
Run Code Online (Sandbox Code Playgroud)

代码搜索具有部分标题"Excel"的窗口,并告诉您是否找到它以及它是否是可见窗口.您应该能够根据自己的目的进行调整.

  • 它是**区分大小写的**,但可以通过将 `GetHandle...` 函数中的 `InStr` 行更改为:`If InStr(1, sStr, sCaption, vbTextCompare) &gt; 0 Then` (2认同)