devxlogo

ExeNameFromWindow – The name of the process that created a window

ExeNameFromWindow – The name of the process that created a window

Const MAX_PATH As Long = 260Private 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_PATHEnd TypePrivate Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hWnd As _    Long, lpdwProcessId As Long) As LongPrivate Declare Function CreateToolhelpSnapshot Lib "Kernel32" Alias _    "CreateToolhelp32Snapshot" (ByVal lFlgas As Long, ByVal lProcessID As Long) _    As LongPrivate Declare Function ProcessFirst Lib "Kernel32" Alias "Process32First" _    (ByVal hSnapshot As Long, procEntry As PROCESSENTRY32) As LongPrivate Declare Function ProcessNext Lib "Kernel32" Alias "Process32Next" _    (ByVal hSnapshot As Long, procEntry As PROCESSENTRY32) As LongPrivate 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

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist