Visual Basic > Forms
Searching a window for a child window
Searching a window for a child window The function below change be used to search a dialog for a specific child window (either by class name or caption). Option Explicit Private Declare Function GetWindow Lib "user32" (ByVal hwnd As Long, ByVal wCmd As Long) As Long Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hwnd As Long, ByVal lpClassName As String, ByVal nMaxCount 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 'Purpose : Enumerates all the child windows and returns the handle of a child window with ' a matching caption or class name. 'Inputs : lParentHwnd The handle to a parent window ' [sClassName] The class name to search for. ' [sCaption] The caption to search for. ' [bSearchChildWindows] Searchs within each child window for a matching window 'Outputs : Returns the handle of child window or zero if not found Function FindChildWindow(ByVal lParentHwnd As Long, Optional ByVal sClassName As String, Optional ByVal sCaption As String, Optional bSearchChildWindows As Boolean = False) As Long Dim bClassMatches As Boolean, bCaptionMatches As Boolean Const clMaxName As Long = 255 Const GW_CHILD = 5 Const GW_HWNDNEXT = 2 Const GW_HWNDFIRST = 0 Dim lWinHwnd As Long, sTestName As String * clMaxName, lNumChars As Long 'Ignore case sClassName = UCase$(sClassName) sCaption = UCase$(sCaption) 'Find the first child window lWinHwnd = GetWindow(lParentHwnd, GW_CHILD) If lWinHwnd = 0 Then Exit Function End If Do bClassMatches = False bCaptionMatches = False lNumChars = clMaxName If Len(sClassName) Then 'Get the child window classname lNumChars = GetClassName(lWinHwnd, sTestName, (clMaxName)) If UCase(Left$(sTestName, lNumChars)) = sClassName Then 'Found matching class name bClassMatches = True End If Else 'No class name specified bClassMatches = True End If If Len(sCaption) Then lNumChars = GetWindowText(lWinHwnd, sTestName, (clMaxName)) If UCase(Left$(sTestName, lNumChars)) = sCaption Then 'Found matching caption bCaptionMatches = True End If Else 'No caption specified bCaptionMatches = True End If If bClassMatches And bCaptionMatches Then 'Found matching dialog, return handle FindChildWindow = lWinHwnd Exit Do ElseIf bSearchChildWindows Then 'Search Child windows FindChildWindow = FindChildWindow(lWinHwnd, sClassName, sCaption, True) If FindChildWindow Then Exit Do End If End If 'Try next next child lWinHwnd = GetWindow(lWinHwnd, GW_HWNDNEXT) If lWinHwnd = 0 Then 'No more child windows Exit Do End If Loop While lWinHwnd 'Loop until there are no more child windows End Function
Visual Basic Codes
ActiveX
Miscellaneous
Applications
Code Snippets
Common Dialogs
Special Effects
Database Stuff
Date Time
Files Drives
Forms
Graphics Games
Internet Stuff
Multimedia
Other
Strings
Windows