Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VB5,VB6
Expertise: Intermediate
Feb 6, 2001

ExeNameFromWindow - The name of the process that created a window

Const MAX_PATH As Long = 260

Private Type PROCESSENTRY32
    dwSize As Long
    cntUsage As Long
    th32ProcessID As Long
    th32DefaultHeapID As Long
    th32ModuleID As Long
    cntThreads As Long
    th32ParentProcessID As Long
    pcPriClassBase As Long
    dwflags As Long
    szexeFile As String * MAX_PATH
End Type

Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hWnd As _
    Long, lpdwProcessId As Long) As Long
Private Declare Function CreateToolhelpSnapshot Lib "Kernel32" Alias _
    "CreateToolhelp32Snapshot" (ByVal lFlgas As Long, ByVal lProcessID As Long) _
    As Long
Private Declare Function ProcessFirst Lib "Kernel32" Alias "Process32First" _
    (ByVal hSnapshot As Long, procEntry As PROCESSENTRY32) As Long
Private Declare Function ProcessNext Lib "Kernel32" Alias "Process32Next" _
    (ByVal hSnapshot As Long, procEntry As PROCESSENTRY32) As Long
Private Declare Sub CloseHandle Lib "Kernel32" (ByVal hPass As Long)

' Get the name of the process that created a window
'
' Works only on Win9x and 2000 (no Windows NT, sorry)

Function ExeNameFromWindow(ByVal hWnd As Long) As String
    Dim threadID As Long
    Dim processID As Long
    Dim hSnapshot As Long
    Dim procEntry As PROCESSENTRY32
    Dim success As Long
    Dim i As Integer
    
    Const TH32CS_SNAPPROCESS As Long = 2&
    
    ' get a snapshot of running processes, exit if error
    hSnapshot = CreateToolhelpSnapshot(TH32CS_SNAPPROCESS, 0&)
    If hSnapshot = -1 Then Exit Function
    
    ' Get ID for window thread, exit if not valid
    threadID = GetWindowThreadProcessId(hWnd, processID)
    If threadID = 0 Or processID = 0 Then Exit Function

    ' we must initialize first DWord of structure with its size
    procEntry.dwSize = Len(procEntry)
    ' get info on first process
    success = ProcessFirst(hSnapshot, procEntry)
    
    Do While success
        If procEntry.th32ProcessID = processID Then
            ' we found it, read name of executable and bail out of the loop
            ExeNameFromWindow = Left$(procEntry.szexeFile, _
                InStr(procEntry.szexeFile & vbNullChar, vbNullChar) - 1)
            Exit Do
        End If
        ' otherwise, continue the search
        success = ProcessNext(hSnapshot, procEntry)
    Loop
    
    ' in all cases, close the shapshot handle
    CloseHandle hSnapshot
    
End Function

Francesco Balena
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date