FindAnyWindow


Lest you think enumerating things has little practical use, I’m going to respond to a challenge I posed in the first edition of this book. I asked readers to send me a FindAnyWindow function that would allow me to use the same wildcard characters recognized by the Like operator. If I wanted to find the first window with the word Fool in the title, I could search like this:

hWnd = FindAnyWindow(“*Fool*”)

Of course, this function would also need to be able to search by class name (we’ll see what a class name is in Chapter 6), and it should have an option to search case-insensitive.

Function FindAnyWindow(Optional Title As String = sNullStr, _
Optional Class As String = sNullStr, _
Optional CaseSense As Boolean = True) As Long

' Pass Title, Class, or both, but not neither
BugAssert Title <> sEmpty Or Class <> sEmpty
' Store parameters in UDT
Dim find As TFindAny, f As Long
find.fCase = CaseSense
find.sClass = IIf(find.fCase, Class, UCase(Class))
find.sTitle = IIf(find.fCase, Title, UCase(Title))
' Ask FindHelper to check each window
f = EnumChildWindows(GetDesktopWindow, AddressOf FindHelper, find)
FindAnyWindow = find.hWndTarget

End Function

I’m still ticked off that no one answered my challenge in the first edition, so I’m going to make you look up the private FindHelper function yourself. It simply gets the class and title variables from the window handle (using techniques described in Chapter 6) and compares them, using the Like operator, to the stored parameters in the find UDT variable. Your challenge for this version is to write a FindAnyWindows function that stores all matching windows, not just the first one, in a collection.


There’s a lot more to say about callback functions, and some of the most important things have to do with receiving window messages. I’ll say some of those things later in “Sending and Receiving Messages” in Chapter 6.