In our applications often need to let users choose directories, such as anti-virus software users choose to process directories and so on. This involves the selection of the directory, and we can use one of the following methods to allow the user to select the directory:
1. Using SHBrowseForFolder and SHGetPathFromIDList functions
The function prototype is stated as follows:
Winshellapi lpitemidlist winapi SHBrowseForFolder (Lpbrowseinfo lpbi);
Winshellapi BOOL winapi SHGetPathFromIDList (lpcitemidlist pidl, LPSTR Pszpath); The structure of Lpbrowseinfo and lpitemidlist refer to the WIN32 documentation. This method selects the directory to obtain all available directories under the Windows desktop, including shared directories for other computers in the Network Neighborhood, but not new directories. The following routine allows the user to select a directory that returns a full path string to the selected directory.
#include < shlobj.h >
Use the WINAPI function to pop up a Select Folder dialog box
Ansistring Selectfolder (ansistring Caption)
{
Browseinfo bi; Controls the structure of properties on the Browse dialog box
Lpitemidlist ItemID;
Char Sdir[max_path]; MAX_PATH: System constant, maximum path length
Char Foldername[max_path];
memset (&bi, 0, sizeof (browseinfo)); Clear Zero
memset (sdir, 0, MAX_PATH);
Bi.hwndowner = application->handle; parent Window Handle
Bi.pszdisplayname = FolderName; Buffer that holds the path
Bi.lpsztitle = Caption.c_str (); dialog box title
Bi.ulflags = Bif_returnonlyfsdirs; Show only file system folders
ItemID = SHBrowseForFolder (&BI);
if (itemid==null)
Return "";
SHGetPathFromIDList (ItemID, sdir);
Globalfreeptr (ItemID);
Ansistring pathname=string (sdir);
if (Pathname.isempty ())
Return "";
if (strcmp (Pathname.ansilastchar (), "\")!=0)
pathname+= "\"; Add a path character
return PathName;
}
//--------------------------------------------------------------------------
We can make the following call to get the selected directory name:
Ansistring Destpathname=selectfolder ("Select the destination directory for gradient data");
2, use the Selectdirectory function.
The function provided by C++builder Selectdirectory can be used to select a directory name that displays a dialog box similar to open/save, but has the advantage of using/not using the keyboard to enter directory names and allowing the creation of new directories, with the disadvantage that the interface is in English. The prototype is defined as follows:
extern PACKAGE bool __fastcall selectdirectory (ansistring &directory, tselectdiropts Options, int helpctx);
The following routine selectdir allows you to select a directory:
#include < FileCtrl.hpp >
AnsiString SelectDir(AnsiString Dir)
{
if(SelectDirectory(Dir, TSelectDirOpts() << sdAllowCreate << sdPerformCreate << sdPrompt,0))
return Dir;
else return "";
}