by Raj Diwate (4 Submissions)
Category: Miscellaneous
Compatability: VB 6.0
Difficulty: Unknown Difficulty
Originally Published: Thu 9th August 2001
Date Added: Mon 8th February 2021
Rating: (1 Votes)
Browse folder dialog box using API
API Declarations
Private Type udtBrowse
lngHwnd 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 Const BIF_RETURNONLYFSDIRS = 1
Private Const MAX_PATH = 260
Private Declare Sub CoTaskMemFree Lib "ole32.dll" _
(ByVal hMem As Long)
Private Declare Function lstrcat Lib "Kernel32" _
Alias "lstrcatA" (ByVal lpString1 As String, _
ByVal lpString2 As String) As Long
Private Declare Function SHBrowseForFolder Lib "shell32" _
(lpbi As udtBrowse) As Long
Private Declare Function SHGetPathFromIDList Lib "shell32" _
(ByVal pidList As Long, ByVal lpBuffer As String) As Long
'on the click event of the command button with a simple code
'Private Sub Command1_Click()
'Dim sPath As String
' sPath = BrowseDialog(Me.hWnd, "Select Folder")
' MsgBox sPath
'End Sub
Public Function BrowseDialog(ByVal lngHwnd As Long, ByVal sMessage As String) As String
On Error GoTo ExitHandler
Dim intNull As Integer
Dim lngIDList As Long, lngResult As Long
Dim strPath As String
Dim udtBI As udtBrowse
'Setting API properties
With udtBI
.lngHwnd = lngHwnd
.lpszTitle = lstrcat(sMessage, "")
.ulFlags = BIF_RETURNONLYFSDIRS
End With
'Displaying the browse folder dialog box...
lngIDList = SHBrowseForFolder(udtBI)
If lngIDList <> 0 Then
'Create string of nulls so it will fill in with the path
strPath = String(MAX_PATH, 0)
'Retrieves the path selected, places in the null
'character filled string
lngResult = SHGetPathFromIDList(lngIDList, strPath)
'Release memory
Call CoTaskMemFree(lngIDList)
'Find the first instance of a null character,
'to get just the path
intNull = InStr(strPath, vbNullChar)
'Greater than 0 means path exists...
If intNull > 0 Then
'Set the value
strPath = Left(strPath, intNull - 1)
End If
End If
'Return the path
BrowseDialog = strPath
Exit Function
ExitHandler:
BrowseDialog = Empty
End Function