2017-01-06 29 views
0

需要幫助獲取主窗口或窗口狀態屬性使用Excel VBA腳本如何使用Excel VBA獲取Windows應用程序主窗口和窗口狀態屬性?

在我的Windows機器上,我有兩個進程以相同的名字運行,例如xyz.exe。

其中一個有Windows應用程序,另一個是幫助程序或後臺進程。我想使用mainwindowtitle或window status屬性來找出哪一個是windows應用程序進程。

我之所以選擇這些屬性是因爲後臺進程沒有主窗口和窗口狀態爲空。下面是顯示兩個進程的進程管理器屏幕截圖。

enter image description here

使用的腳本和應用程序WMI任務我可以很容易找到進程ID,但我無法弄清楚如何獲得mainwindowtitle或窗口狀態屬性。

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 
+3

你知道窗口的標題?如果是這樣,你可以使用WinAPI'FindWindow'函數。 –

+0

由於標題可能會根據打開的文件名稱更改,因此可能無法正常工作。 – ravi

+1

理論上,您應該能夠從ProcessID獲取句柄,然後使用WinAPI函數從句柄中獲取窗口標題。儘管我現在無法得到這個工作。 –

回答

1

基於什麼大衛在評論中提到,試試這個:

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" `enter code here`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 
+0

看起來應該可以工作。讓我試試看。 – ravi

+0

它的工作原理。謝謝 – ravi

相關問題