如何使用ExcelVBA获取Windows应用程序主window标题和window状态属性?

How to get Windows application process mainwindowtitle and window status properties using Excel VBA?

需要帮助使用 Excel VBA 脚本?[=16= 获取主要window标题或 window 状态属性]

在我的 windows 机器上,我有两个 运行 同名的进程,例如xyz.exe.

其中一个有 windows 应用程序,另一个是帮助程序或后台进程。我想使用 mainwindowtitle 或 window status 属性找出哪个是 windows 应用程序进程。

我之所以选择这些属性是因为后台进程没有主window标题并且window状态为空。下面是显示这两个进程的进程资源管理器屏幕截图。

使用脚本和应用程序的 WMI 任务我可以很容易地找出进程 ID,但我无法弄清楚如何获得主要window标题或window状态属性.

Private Sub getP()       
    strComputer = "."
    sExeName = "XYZ.exe"

    Set objWMIService = GetObject("winmgmts:\" & strComputer & "\root\CIMV2")
    Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Process 
    WHERE Name = '" & sExeName & "'", , 48)

    For Each objItem In colItems
      Debug.Print "ProcessId: " & objItem.ProcessId
    Next
End Sub

根据 David 在评论中提到的内容,试试这个:

Private Const GW_HWNDNEXT = 2
Private Declare Function GetWindow Lib "user32" (ByVal hWnd As Long, ByVal wCmd As Long) As Long
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long

Sub ListWins(Optional Title = "*XYZ*", Optional Class = "*")
    Dim hWndThis As Long
    hWndThis = FindWindow(vbNullString, vbNullString)
    While hWndThis
        Dim sTitle As String, sClass As String
        sTitle = Space$(255)
        sTitle = Left$(sTitle, GetWindowText(hWndThis, sTitle, Len(sTitle)))
        sClass = Space$(255)
        sClass = Left$(sClass, GetClassName(hWndThis, sClass, Len(sClass)))
        If sTitle Like Title And sClass Like Class Then
            Debug.Print sTitle, sClass
        End If
        hWndThis = GetWindow(hWndThis, GW_HWNDNEXT)
    Wend
End Sub