Want to get up to speed on the latest Visual Basic programming? Includes Visual Basic 6 and Visual InterDev 6. Check out our training programs at http://www.codeoftheweek.com/vbtraining.html
If you would like to get paid for surfing the web, jump to http://www.codeoftheweek.com/paidsurf.html
This issue introduces a module which shows how retrieve a window by its caption. Normally this is a simple API call. The biggest problem with the standard FindWindow API call is that the caption of the window passed to the routine much match exactly. Our routine uses the built-in pattern matching of Visual Basic to provide a very flexible way to find a window which is currently open.
A good use of this routine is a simple routine to wait for a particular window to show up after running a Shell command.
If you have any questions about using this module, let us know at questions@codeoftheweek.com
Public Function WindowCaption(ByVal hWnd As Long) As String
Returns a window caption by its handle. This routine strips out any nulls the API puts at the end of the string.
Public Function FindAnyTopWindow(sCaption As String) As Long
This routine does all the work. It will search through all the child windows of the desktop window to find a window which has the caption specified by sCaption. You can pass strings which contain the Visual Basic pattern matching characters. For example, "Microsoft Word*" will find the first open instance of Word regardless of what file you happen to have open in Word.
A zero will be returned if there were no matches.
See above descriptions.
This sample assumes you have a form with a text box control called txtCaption and two label controls called lblCaption and lblHwnd. The sample will take the input from txtCaption and search for that window. It will set lblCaption with the full caption it found and lblHwnd with the handle to the window it found.
' This code would probably appear within a button or a background routine. Dim hWnd As Long hWnd = FindAnyTopWindow(txtCaption.Text) If hWnd = 0 Then lblCaption = "" lblHwnd = 0 Else lblCaption = WindowCaption(hWnd) lblHwnd = hWnd End If
To see the source code for this issue you must be a subscriber to Code of the Week. If you are a subscriber the source code is available at the following address: http://www.codeoftheweek.com/membersonly/bi/0101.html