#include once "window9.bi"

Function BrowseCallbackProc(byval hWnd   as HWND, _
                            byval uMsg   as UINT, _ 
                            byval lParam as LPARAM, _
                            byval lpData as LPARAM) as integer 
  select case uMsg 
  case BFFM_INITIALIZED 
     SendMessage( hWnd, BFFM_SETSELECTION, -1, lpData ) 
  case BFFM_SELCHANGED 
     dim as zstring * MAX_PATH sPath
    if SHGetPathFromIDList( cast( LPCITEMIDLIST, lParam ), sPath) = 0 then 
      sPath = "Unknown"
    else 
      sPath = "PATH: " + sPath
    end if 
    SendMessage( hWnd, BFFM_SETSTATUSTEXT, 0, cuint( StrPtr(sPath) ) )
   end select 
   function = 0 
end function 

function ShellFolder(byval NameDialog as string, ByVal DefaultFolder as String, ByVal FlagOption As Integer=BIF_RETURNONLYFSDIRS Or BIF_USENEWUI) as string Export
  static sFolder as string
  dim bi         as BROWSEINFO
  dim pidlReturn as LPITEMIDLIST
  dim pidlStart  as LPITEMIDLIST
  Dim hwnd As HWND=0

  CoInitialize( NULL ) 
  SHGetSpecialFolderLocation( NULL, CSIDL_DRIVES, @pidlStart ) 
  sFolder = DefaultFolder
  with bi
    .pidlRoot   = pidlStart 
    .hwndOwner  = hWnd 
    .lpszTitle  = Cast(LPCSTR,StrPtr(NameDialog))
    .ulFlags    =  FlagOption
    .lpfn       = @BrowseCallbackProc 
    .lParam     = cuint( strptr( sFolder ) )
  end with
  pidlReturn = SHBrowseForFolder( @bi ) 
  CoTaskMemFree(pidlStart)

  if( pidlReturn <> NULL ) Then 
    dim as zstring * MAX_PATH path
    SHGetPathFromIDList( pidlReturn, path ) 
    CoTaskMemFree( pidlReturn ) 
    function = path
  else
    function = ""
  end if 
  CoUninitialize( ) 
end Function

