Wednesday, December 17, 2008

[vb6] Prompt for a folder

You can use the shell library to prompt the user for a folder name, like you see in setup programs. The shell function SHBrowseForFolder pops up a modal dialog box that prompts the user to select a folder. (You will probably need only a subset of the constants. See the Platform SDK for an explanation of when to use the differenct flags).
    Private Const BIF_RETURNONLYFSDIRS = &H1&
Private Const BIF_DONTGOBELOWDOMAIN = &H2&
Private Const BIF_STATUSTEXT = &H4&
Private Const BIF_RETURNFSANCESTORS = &H8&
Private Const BIF_EDITBOX = &H10&
Private Const BIF_VALIDATE = &H20&
Private Const BIF_BROWSEFORCOMPUTER = &H1000&
Private Const BIF_BROWSEFORPRINTER = &H2000&
Private Const BIF_BROWSEINCLUDEFILES = &H4000&

Private Type BROWSEINFO
hwndOwner As Long
LPCITEMIDLIST As Long
lpszDisplayName As String
lpszTitle As String
ulFlags As Long
lpfn As Long
lParam As Long
iImage As Long
End Type

Private Declare Function SHBrowseForFolder Lib "shell32.dll" _
(lpbi As BROWSEINFO) As Long
Private Declare Function SHGetPathFromIDList Lib "shell32.dll" _
(ByVal pidl As Long, ByVal sFolder As String) As Long

Private Function PromptForFolder() As String
Dim bInfo As BROWSEINFO
With bInfo
.hwndOwner = hwnd
.lpszDisplayName = String(260, 32)
.lpszTitle = "Select Directory:"
.ulFlags = BIF_RETURNONLYFSDIRS
.lpfn = 0
End With

Dim retval As Long, foldername As String
foldername = String(260, 32)
retval = SHBrowseForFolder(bInfo)
retval = SHGetPathFromIDList(retval, foldername)
PromptForFolder = RTrim$(foldername)
End Function
The VB function as shown returns the full path to the folder. If you want just the name of the folder, return bInfo.lpszDisplayname instead.

1 comment:

  1. Hello, Thanks for the code.
    For much more advanced functionality such as filtering and custom items and checkboxes, etc, see FolderView control from http://www.ssware.com/fldrview.htm

    It is a reusable control so it can be put right inside your own form or dialog.

    ReplyDelete