Rubrik: System/Windows · Prozesse/Tasks | VB-Versionen: VB4, VB5, VB6 | 14.07.04 |
Von der Prozess-ID zum Fenstertitel Diesmal erfahren Sie, wie man anhand der Prozess-ID das dazugehörige Fenster bzw. dessen Fenstertitel ermitteln kann. | ||
Autor: Dieter Otter | Bewertung: | Views: 23.050 |
www.tools4vb.de | System: Win9x, WinNT, Win2k, WinXP, Win7, Win8, Win10, Win11 | Beispielprojekt auf CD |
Frage: Wie kommt man von der Prozess-ID zum Fenstertitel der dazugehörigen Anwendung?
Nachfolgender Tipp verrät wie's geht
' benötigte API-Deklarationen Private Declare Function GetWindowThreadProcessId Lib "user32" ( _ ByVal hwnd As Long, _ lpdwProcessId 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 GetWindow Lib "user32" ( _ ByVal hwnd As Long, _ ByVal wCmd As Long) As Long Private Declare Function GetParent Lib "user32" ( _ ByVal hwnd 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 Private Const GW_HWNDNEXT = 2
' Ermittelt das Fensterhandle anhand einer Prozess-ID Private Function ProcID2hWnd(ByVal ProcID As Long) As Long ' alle Fenster durchlaufen und nach Process-ID suchen Dim lngHWnd As Long Dim lngProcTaskID As Long lngHWnd = FindWindow(vbNullString, vbNullString) Do While lngHWnd <> 0 ' Existiert kein Eltern-Fenster, dann ProcssID ' ermitteln und vergleichen If GetParent(lngHWnd) = 0 Then GetWindowThreadProcessId lngHWnd, lngProcTaskID ' Handelt es sich um den gesuchten Prozess? If lngProcTaskID = ProcID Then ' Fenster-Handle zurückgeben und Schleife ' verlassen! ProcID2hWnd = lngHWnd Exit Do End If End If ' Nächstes Fenster lngHWnd = GetWindow(lngHWnd, GW_HWNDNEXT) Loop End Function
Beispiel für den Aufruf:
Dim nHWnd As Long Dim sTitle As String Dim nResult As Long Dim nProcessID As Long ' Notepad starten nProcessID = Shell("notepad.exe") ' Fensterhandle anhand ProcessID ermitteln nHWnd = ProcID2hWnd(nProcessID) If nHWnd <> 0 Then ' und jetzt den Fenstertitel auslesen sTitle = Space$(255) nResult = GetWindowText(nHWnd, sTitle, Len(sTitle)) If nResult > 0 Then sTitle = Left$(sTitle, nResult) MsgBox sTitle End If End If