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

标签 excel vba

我使用 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/

相关文章:

string - 使用 VBA 将可变文本字符串(时间戳)插入单元格

vba - Excel 2007 VBA - Avaya CMS - SSH 破坏脚本

vba - 使用 VBA 创建 Excel 2007 或 2010 自定义任务 Pane

vba - 创建嵌套类

c# - 如何以编程方式检查电脑上是否存在 MS Excel?

VBA UBound 函数

excel - VBA - 第二个窗口最大化时连接范围计数不正确

excel - 删除表中的最后一行 vba

excel - Access vba字典

java - 在Java中读取xlsx复选框值