Search code examples
vbaexcelwin32-process

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


Need help getting mainwindowtitle or window status properties using Excel VBA script?

On my windows machine I have two processes running with same name e.g. xyz.exe.

One of them has windows application and the other is kind of helper or background process. I want to find out which one is the windows application process using mainwindowtitle or window status properties.

The reason I chose these properties because background process has no mainwindowtitle and window status is null. Below is the process explorer screen shot showing the two processes.

enter image description here

Using WMI Tasks for Scripts and Applications I can easily find out the process ids but I am not able to figure out how to get the mainwindowtitle or window status property.

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

Solution

  • Based on what David mentioned in comment, try this:

    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