#include "Common.ch"
#include "bap.ch"
#include "Dll.ch"

#define BIF_RETURNONLYFSDIRS   0x0001  // For finding a folder to start document searching
#define BIF_DONTGOBELOWDOMAIN  0x0002  // For starting the Find Computer
#define BIF_STATUSTEXT         0x0004
#define BIF_RETURNFSANCESTORS  0x0008
#define BIF_EDITBOX            0x0010
#define BIF_VALIDATE           0x0020  // insist on valid result (or CANCEL)
#define BIF_NEWDIALOGSTYLE     0x0040  // Use the new user interface. Setting this flag provides the user with a larger dialog box that can be resized.
#define BIF_BROWSEFORCOMPUTER  0x1000  // Browsing for Computers.
#define BIF_BROWSEFORPRINTER   0x2000  // Browsing for Printers
#define BIF_BROWSEINCLUDEFILES 0x4000  // Browsing for Everything

Procedure Main()
LOCAL path, oDlg
oDlg := XbpDialog():new(,,,{800,600}):create()
CenterControl(oDlg)
SetAppWindow(oDlg:drawingArea)
Path := BrowseForFolder( oDlg, "Select Folder", .T., .T. )

Confirmbox(NIL, ('Path' + Chr(13) + Path))
RETURN

FUNCTION BrowseForFolder( oWin, cPrompt, lEditBox, lValidate )

   LOCAL hWnd      := IIF(oWIn=NIL,SetAppWindow():getHWND(),oWin:getHWND())
   LOCAL aOFN
   LOCAL cOFN
   LOCAL nFlags    := BIF_NEWDIALOGSTYLE
   LOCAL ret       := ''
   LOCAL nIDL      := 0
   LOCAL cFolderName

   DEFAULT lEditBox TO  .F.
   DEFAULT lValidate TO .F.

   cFolderName := replicate(chr(0),260)

   cPrompt = ConvToAnsiCP(IIF(cPrompt=NIL,'',cPrompt)+CHR(0))
   IF lEditBox
      nFlags := nFlags+BIF_EDITBOX
   ENDIF
   IF lValidate
      nFlags := nFlags+BIF_VALIDATE
   ENDIF

   aOFN = BaInit(8)

   BaStruct(aOFN,hWnd)                          // hwndOwner
   BaStruct(aOFN,NIL)                           // pidlRoot
   BaStruct(aOFN,@cFolderName)                  // lpstrFolder
   BaStruct(aOFN,@cPrompt)                      // lpstrPrompt
   BaStruct(aOFN,nFlags)                        // nFlags
   BaStruct(aOFN,0)                             // CallBackProc
   BaStruct(aOFN,0)                             // lParam
   BaStruct(aOFN,0)                             // iImage

   cOFN = BaAccess(aOFN)

   nIDL = SHBrowseForFolder(cOFN)

   IF nIDL > 0
      SHGetPathFromIDList(nIDL,@cFolderName)
      CoTaskMemFree(nIDL)
      ret = ConvToOEMCP(substr(cFolderName,1,at(chr(0),cFolderName)-1))
   ENDIF

RETURN(ret)

DLLFUNCTION SHBrowseForFolder( cStru ) USING STDCALL FROM SHELL32.DLL
DLLFUNCTION SHGetPathFromIDList(pidl,@cFolderName) USING STDCALL FROM SHELL32.DLL
DLLFUNCTION CoTaskMemFree(p) USING STDCALL FROM OLE32.DLL
