Thanks to Matt Hernandez.
Use the GetWindow API function to enumerate the system's windows looking for visible top-level windows.
Use GetWindow to get the first desktop child window. Use GetWindow to iterate through the windows. Ignore those without titles, those that are invisible, those that are owned by another window, and ProgMan.
|
Sub ListToplevelWindows(ByVal lst As ListBox)
Dim hwndFirstTopLevel As Long
hwndFirstTopLevel = GetWindow(GetDesktopWindow, _
GW_CHILD)
Call FindTopLevelWindows(hwndFirstTopLevel, lst)
End Sub
Function WindowTextFromWnd(ByVal hwnd As Long) As String
'Receives a handle to a window and returns the window
' text from that window as a string
Dim WTextLen As Integer
Dim sTitle As String
Dim Caption As String
Caption = String$(500, 0)
txlen = GetWindowTextLength(hwnd)
WTextLen = GetWindowText(hwnd, Caption, txlen + 1)
sTitle = Left$(Caption, WTextLen)
WindowTextFromWnd = sTitle
End Function
Sub FindTopLevelWindows(hwnd As Long, ByVal lst As ListBox)
Dim chkBlank As Boolean, chkInvisible As Boolean, _
chkOwned As Boolean
Dim count As Integer, szWindowText As String
'This basic idea for this function was on the MSDN
' Library CD...
' from the book "Hardcore Visual Basic". It was called
' "RefreshTopWinList",
' and it used to add all windows that match a certain
' criteria to a list,
' but I tweaked it some for this example
chkBlank = False
chkInvisible = False
chkOwned = True
count = 0
Do While hwnd <> 0&
' Determine whether to display titled, visible, and
' unowned
If IsVisibleTopWnd(hwnd, chkBlank, chkInvisible, _
chkOwned) Then
szWindowText = WindowTextFromWnd(hwnd)
' This condition is simply to exclude "this"
' program and Progman...but do as you like
If szWindowText <> "ListTopLevel" And _
szWindowText <> "Program Manager" Then
lst.AddItem szWindowText
End If
hwnd = GetWindow(hwnd, GW_HWNDNEXT)
End If
' Get next child
hwnd = GetWindow(hwnd, GW_HWNDNEXT)
Loop
End Sub
Function IsVisibleTopWnd(hwnd As Long, _
Optional IgnoreEmpty As Boolean = False, _
Optional IgnoreVisible As Boolean = False, _
Optional IgnoreOwned As Boolean = False) _
As Boolean
'This function was on the MSDN Library CD in the book
' "Hardcore Visual Basic",
' and I don't think changed it at all
If IgnoreEmpty Or WindowTextFromWnd(hwnd) <> "" Then
If IgnoreVisible Or IsWindowVisible(hwnd) Then
If IgnoreOwned Or GetWindow(hwnd, GW_OWNER) = _
0& Then
IsVisibleTopWnd = True
End If
End If
End If
End Function
|