VB 程序设计

10个成员

在VB中直接用ODBC API访问数据库

发表于 2016-12-25 3774 次查看
  从WINDOWS 95开始,微软为我们提供了一个好用的文件搜索器。使用这个搜索器,我们可以方便快捷的查找到符合条件的文件。但有时我们在程序设计中也需要这一功能,能否在自己的程序中实现呢?答案当然是肯定的。下面我们就来着手设计一个VB程序中的文件搜索器。

  首先,进入VB中,建立一个新的表单。在表单上建立一个驱动器列表框(DriveList),一个目录列表框(FolderList),一个检查框(SubCheck),一个ListView控件(FileList),两个文本框(FileName,FileSize)和两个按钮(cmdSearch,cmdExit)。需要注意的是ListView 控件是 Mscomctl.ocx 文件中一组 ActiveX 控件的一部分。若要在应用程序中使用 ListView 控件,必须将 Mscomctl.ocx 文件添加到工程中。选择ListView控件,点击鼠标右键,在弹出菜单中选择“属性”。在属性窗口的“列首”页中设置将要显示的列,连续按动“插入列”5次。排列好各控件的位置,然后加入以下代码:

Option Explicit
Dim FileSys As Scripting.FileSystemObject

Private Sub CmdExit_Click()
End
End Sub

Private Sub DriveList_Change()
FolderList.Path = DriveList
End Sub

Private Sub Form_Load()
Dim I As Integer
Set FileSys = New Scripting.FileSystemObject
FolderList.Path = Left(DriveList.Drive, 2) & "\"
With FileList.ColumnHeaders.Item(1)
.Alignment = lvwColumnLeft
.Text = "文件名"
.Width = 2000
End With
With FileList.ColumnHeaders.Item(2)
.Alignment = lvwColumnRight
.Text = "大小(KB)"
.Width = 1500
End With
With FileList.ColumnHeaders.Item(3)
.Alignment = lvwColumnLeft
.Text = "类型"
.Width = 1500
End With
With FileList.ColumnHeaders.Item(4)
.Alignment = lvwColumnLeft
.Text = "路径"
.Width = 2000
End With
With FileList.ColumnHeaders.Item(5)
.Alignment = lvwColumnLeft
.Text = "修改时间"
.Width = 2000
End With
End Sub

Private Sub Form_Unload(Cancel As Integer)
Set FileSys = Nothing
End Sub

Private Sub cmdSearch_Click()
Dim SFolderStart As Scripting.Folder
Set SFolderStart = FileSys.GetFolder(FolderList.Path)
FileList.ListItems.Clear
AddFiles SFolderStart
If FileList.ListItems.Count = 0 Then MsgBox _
"没找到任何符合条件的文件!",vbOKOnly + vbInformation, "提示信息"
End Sub

Private Sub AddFiles(SFolderSearch As Scripting.Folder)
Dim SFolder As Scripting.Folder
Dim SFile As Scripting.File
Dim sngFileSize As Single
Dim lngSize As Long
Dim Itm As ListItem
If SubCheck.Value = 1 Then
If SFolderSearch.SubFolders.Count Then
For Each SFolder In SFolderSearch.SubFolders
AddFiles SFolder
Next SFolder
End If
End If
sngFileSize = FileSize * 1000
For Each SFile In SFolderSearch.Files
With SFile
If .Size >= sngFileSize And IIf(FileName.Text < > "", _
InStr(.Name, FileName.Text) > 0, True) Then
Set Itm = FileList.ListItems.Add(Text:=.Name)
lngSize = .Size / 1000
With Itm
.SubItems(1) = Format(lngSize, "#,###")
.SubItems(2) = SFile.Type
.SubItems(3) = SFile.ParentFolder
.SubItems(4) = SFile.DateLastModified
End With
End If
End With
Next SFile
Set Itm = Nothing
Set SFolder = Nothing
End Sub
  运行后,选择相应目录,再在FileName文本框中输入要查找的文件名或文件名的一部分,然后再在FileSize文本框中输入文件的大小,按下搜索按钮即可搜索到相应文件。当然,这只是个功能较为简单的文件搜索器,有兴趣的读者可以使用Scripting.FileSystemObject对象的属性为其添加一些更为有用的功能。

  本例程序在Visual Basic 4.0、Windows 95环境下调试通过。

 

发表回复
你还没有登录,请先登录注册