home account info subscribe login search My ITKnowledge FAQ/help site map contact us


 
Brief Full
 Advanced
      Search
 Search Tips
To access the contents, click the chapter and section titles.

Visual Basic 6 Programming Blue Book: The Most Complete, Hands-On Resource for Writing Programs with Microsoft Visual Basic 6!
(Publisher: The Coriolis Group)
Author(s): Peter G. Aitken
ISBN: 1576102815
Publication Date: 08/01/98

Bookmark It

Search this book:
 
Previous Table of Contents Next


Listing 14.8 The StartSearch procedure.

Private Sub StartSearch()

‘ We come here to start a search.

‘ Empty the List Box.
lstFiles.Clear

‘ Clear the Halt flag.
Halt = False

‘ Disable all controls except the Stop button.
Command1(0).Enabled = False
Command1(1).Enabled = True
Command1(2).Enabled = False
Drive1.Enabled = False
dirStart.Enabled = False
txtPattern.Enabled = False

‘ If the invisible Dir list is already pointing to
‘ the same directory as the visible Dir list, we must
‘ trigger a Change event. If not, change its Path property,
‘ which will automatically trigger a Change event.

‘ It is the dirHidden.Change event that triggers the search process.

‘ Display the hourglass mouse pointer.
Screen.MousePointer = 11

If dirHidden.Path = dirStart.Path Then
    dirHidden_Change
Else
    dirHidden.Path = dirStart.Path
End If

‘ We reach here after the search is complete.
‘ Re-enable all controls except the Stop button.
Screen.MousePointer = 0
Command1(0).Enabled = True
Command1(1).Enabled = False
Command1(2).Enabled = True
Drive1.Enabled = True
dirStart.Enabled = True
txtPattern.Enabled = True

End Sub

As noted earlier, the search begins when the hidden DirListBox’s Change event procedure is triggered. Listing 14.9 shows the code in that procedure. The code here is really simpler than it looks. The first step is to search the current folder (the one you just changed to) for files that match the search template entered by the user. The path is placed in the List Box, then a loop obtains the names of all matching files by calling the Dir function repeatedly. These names are also added to the List Box, along with file information if the FileInfo option is selected. Note the Visual Basic functions called FileDateTime and FileLen; these are available for obtaining the desired information about the file.

Once all of the files in the current folder have been processed, the attention turns to any subfolders. Remember, the DirListBox’s ListCount property will tell us the number of subfolders. By using that value—plus the control’s List indexed property—you can loop through the list of subfolders and place them in an array.

When this array is loaded with the names of any subfolders in the current folder, the rest is easy. Set up a loop that goes through the array, assigning each subfolder name (which includes the full path) to the hidden DirListBox’s Path property. Guess what? Each time you do this, you trigger another Change event procedure, repeating the entire process I have just described.

Listing 14.9 The hidden DirListBox’s Change event procedure.

Private Sub dirHidden_Change()

‘ Triggered when the hidden directory list changes. It is here
‘ that the actual search is performed.

Dim Path As String, FileName As String
Dim FileName1 As String, Path1 As String, Entry As String
Dim NumDirs As Integer, X As Integer, Y As Integer
Dim DirAdded As Boolean, Spaces As Integer

Depth = Depth + 1

‘ For testing as described in text, uncomment the next line.
debug.Print “Depth = ”, Depth

‘ Get the current path and add a backslash if necessary.
Path = dirHidden.Path
If Right(Path, 1) <> “\” Then
    Path = Path & “\”
End If

‘ Create the full search pattern by combining the current path
‘ with the file pattern from the txtPattern Text Box.
Path1 = Path & txtPattern.TEXT

‘ The Dir function returns an empty string if
‘ a matching file is not found, and the file name if
‘ a matching file is found.
FileName = Dir(Path1)
DirAdded = False

‘ Loop as long as a matching file is found.
Do Until FileName = “”

    ‘ If the directory name has not already been added to the
    ‘ List Box, add it now.
    If (DirAdded = False) Then
        lstFiles.AddItem “[ “ & dirHidden.Path & ” ]”
        DirAdded = True
    End If

    ‘ Start building the next List Box entry.
    Entry = “    ” & FileName

    ‘ If the FileInfo check box is checked, add the
    ‘ file’s date, time, and length to the entry.
    If chkFileInfo.VALUE Then
        FileName1 = Path & FileName
        Spaces = 16,,Len(FileName)
        Entry = Entry & Space(Spaces) & FileDateTime(FileName1)
        Spaces = 20,,Len(FileDateTime(FileName1))
        Entry = Entry & Space(Spaces) & FileLen(FileName1)
    End If

    ‘ Add the entry to the List Box.
    lstFiles.AddItem Entry

    ‘ Look for the next matching file.
    FileName = Dir
Loop

‘ How many subdirectories are in the current directory?
NumDirs = dirHidden.ListCount

‘ Put the subdirectory names in an array.
ReDim DirList(NumDirs) As String

For X = 0 To NumDirs-1
    DirList(X) = dirHidden.List(X)
Next X

‘ For each subfolder, repeat the search process. Call DoEvents
‘ to enable user to abort the search by clicking the Stop
‘ Command button.
For X = 0 To NumDirs-1
    dirHidden.Path = DirList(X)
    Y = DoEvents()
    If Halt Then
        Exit Sub
    End If
Next X

Depth = Depth-1

End Sub

Exploring The Recursive Algorithm

When considering how recursion works, you must understand that when a function calls itself—which is what the Change event procedure does by changing the control’s Path property—each call results in a completely new and separate copy of the procedure being executed. Each of these copies has its own independent array of subfolder names, as well as its own set of other local variables. Each copy of the Change event procedure sits waiting until the “lower” copies of the procedure have completed (by running out of subfolders to process). Then execution returns to the specific copy of the procedure and continues there until its array of subfolders is exhausted, at which time execution passes “up” one more level. Only when each and every subfolder below the starting subfolder has been processed does execution return to the StartSearch procedure.

To get a feel for what’s happening, use the debug.Print statement to display the value of the Depth variable by uncommenting the line of code near the start of the Change event procedure. You’ll see a sequence of values displayed in the Debug window similar to this:

1
2
3
3
2
3
3
4
4
3
2

At each iteration, the value displayed gives us a feeling for how many “layers” of Change event procedures exist—each with its own array of subfolders. Once you understand the basic principle behind iterative algorithms, you’ll probably find other programming challenges to which they can be applied.

This project requires a bit more code, shown in Listing 14.10. Nothing here is too complicated. You should be able to figure out how it works from the comments in the listing. Before focusing on Listing 14.10, take a look at Figure 14.5, which shows the File Finding utility in operation.

I have found the File Finding utility to be very handy. Actually, I don’t often use it as a standalone program, but I have incorporated its algorithm and code into other projects. For example, you can use the three file-related controls plus the file-finding techniques presented here to create a File Open dialog box that permits the user to locate files anywhere on the disk.

This project is an excellent example of using creative thinking to find a use for a Visual Basic control that its creators probably never envisioned. Many other possibilities are waiting in the Visual Basic toolbox, but remember, a working knowledge of the tools is a prerequisite for getting the most out of them.

Listing 14.10 The remaining code in FINDFILE.FRM.

Private Sub Drive1_Change()

‘ If the user changes drives, pass the new path
‘ to the Dir list control.

dirStart.Path = Drive1.Drive

End Sub

Private Sub Form_Load()

Halt = False
txtPattern.TEXT = “*.EXE”
lstFiles.Clear
depth = 0

End Sub

Private Sub Text1_GotFocus()

‘ Highlight entire contents of Text Box.

txtPattern.SelStart = 0
txtPattern.SelLength = Len(txtPattern.TEXT)

End Sub

Private Sub txtPattern_GotFocus()

‘ Highlight Text Box contents when it gets the focus.

txtPattern.SelStart = 0
txtPattern.SelLength = Len(txtPattern.TEXT)

End Sub


Figure 14.5  The File Finding utility in operation.


Previous Table of Contents Next


Products |  Contact Us |  About Us |  Privacy  |  Ad Info  |  Home

Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc.
All rights reserved. Reproduction whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement.