Wednesday, August 05, 2009


Sample code on how to use SHGetFolderLocation, shamelessly copied from this link. This code was verified to work in Windows 2000 and VB SP6.
Private Declare Function SHGetFolderLocation Lib "shell32.dll" (ByVal hwndOwner As Long, ByVal nFolder As Long, ByVal hToken As Long, ByVal dwReserved As Long, ppidl As Long) As Long
Private Declare Function SHBrowseForFolder Lib "shell32.dll" (lpbi As BROWSEINFO) As Long
Private Declare Function SHGetPathFromIDList Lib "shell32.dll" Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
Private Declare Sub CoTaskMemFree Lib "ole32.dll" (ByVal pv As Long)

  hwndOwner As Long
  pidlRoot As Long
  pszDisplayName As String
  lpszTitle As String
  ulFlags As Long
  lpfn As Long
  lParam As Long
  iImage As Long
End Type
Private Sub Command1_Click()
' This code is licensed according to the terms and conditions listed here.

' Open the Browse for Folder dialog box and display both the display name and
' the actual name of the folder (if it is not a virtual folder).  Any folder under My Computer
' may be selected.
Dim bi As BROWSEINFO  ' structure passed to the function
Dim pidl As Long  ' PIDL to the user's selection
Dim physpath As String  ' string used to temporarily hold the physical path
Dim retval As Long  ' return value

' Initialize the structure to be passed to the function.
bi.hwndOwner = Form1.hWnd  ' window Form1 is the owner of the dialog box
' Specify the My Computer virtual folder as the root
retval = SHGetFolderLocation(Form1.hWnd, CSIDL_DRIVES, 0, 0, bi.pidlRoot)
' Make room in the buffer to get the [virtual] folder's display name
bi.pszDisplayName = Space(260)
bi.lpszTitle = "Please choose a folder."  ' Message displayed to the user
bi.ulFlags = 0  ' no flags are needed here
bi.lpfn = 0  ' no callback function is being used
bi.lParam = 0  ' not needed
bi.iImage = 0  ' this will be set by the function

' Open the Browse for Folder dialog box.
pidl = SHBrowseForFolder(bi)
' If the user selected something, display its display name
' and its physical location on the system.
If pidl <> 0 Then
  ' Remove the empty space from the display name variable.
  bi.pszDisplayName = Left(bi.pszDisplayName, InStr(bi.pszDisplayName, vbNullChar) - 1)
  Debug.Print "The user selected: "; bi.pszDisplayName
  ' If the folder is not a virtual folder, display its physical location.
  physpath = Space(260)  ' make room in the buffer
  retval = SHGetPathFromIDList(pidl, physpath)
  If retval = 0 Then
    Debug.Print "Physical Location: (virtual folder)"
    ' Remove the empty space and display the result.
    physpath = Left(physpath, InStr(physpath, vbNullChar) - 1)
    Debug.Print "Physical Location: "; physpath
  End If
  ' Free the pidl returned by the function.
  CoTaskMemFree pidl
End If

' Whether successful or not, free the PIDL which was used to
' identify the My Computer virtual folder.
CoTaskMemFree bi.pidlRoot

End Sub


No comments: