Using SHBrowseForFolder in VB6, a Directory Browser / Selection Tool.
Published : 13.Jun.2005
One of the things many windows applications need is a browsable directory control, so that the user can select which directory to find files in. I had looked at using this common replacement control, however its another OCX that would need deploying with the application. Finally I decided to use the SHBrowseForFolder function, which is already part of the Windows API and wouldn't need any extra controls to be deployed.
Setting up Visual Basic to use the SHBrowseForFolder Function
The first step is to create the 3 Const shown below along with the user Type BrowseInfo. You also need to declare the 3 functions from both the shell32 and kernel32 libraries.
Option Explicit
Private Const BIF_RETURNONLYFSDIRS = 1
Private Const BIF_DONTGOBELOWDOMAIN = 2
Private Const MAX_PATH = 260
Private Type BrowseInfo
hwndOwner As Long
pIDLRoot As Long
pszDisplayName As Long
lpszTitle As Long
ulFlags As Long
lpfnCallback As Long
lParam As Long
iImage As Long
End Type
Private Declare Function SHBrowseForFolder
Lib "shell32" (lpbi As BrowseInfo) As Long
Private Declare Function SHGetPathFromIDList
Lib "shell32" (ByVal pidList As Long,
ByVal lpBuffer As String) As Long
Private Declare Function lstrcat Lib "kernel32"
Alias "lstrcatA" (ByVal lpString1 As String,
ByVal lpString2 As String) As Long
OpenDirectoryTV Function
Next you need to copy and paste the OpenDirectoryTV function show below, this function takes one optional parameter which is used for setting the title of the browse dialog. You will need to change the .hwndOwner line so that it is linked to the .hWnd property of one your forms, in this example its linked to frm_shbrowseforfolder.hWnd.
Public Function OpenDirectoryTV(Optional odtvTitle As String) As String
Dim lpIDList As Long
Dim sBuffer As String
Dim szTitle As String
Dim tBrowseInfo As BrowseInfo
szTitle = odtvTitle
With tBrowseInfo
.hwndOwner = frm_shbrowseforfolder.hWnd
.lpszTitle = lstrcat(szTitle, "")
.ulFlags = BIF_RETURNONLYFSDIRS
End With
lpIDList = SHBrowseForFolder(tBrowseInfo)
If (lpIDList) Then
sBuffer = Space(MAX_PATH)
SHGetPathFromIDList lpIDList, sBuffer
sBuffer = Left(sBuffer, InStr(sBuffer, vbNullChar) - 1)
OpenDirectoryTV = sBuffer
End If
End Function
Example Usage
Below is a simple example showing how to invoke the function, and return the selected folder into a variable called folder.
Private Sub cmd_browse_Click()
Dim folder As String
folder = OpenDirectoryTV("Select Folder")
If folder <> "" Then
MsgBox "You selected : " & folder
End If
End Sub
