Delphi source code :

Select (browse for) folder


With the Delphi function SelectDirectory you can let the user select or enter a folder name ("directory"). There are two syntaxes:

1. SelectDirectory( Title, RootDir, DirSelected ) displays the standard Windows "Browse for Folder" dialog with a directory tree. The parameters are:

  • Title: the title that should appear above the directory tree.
  • RootDir: the directory to be used as the root of the directory tree that is shown.
  • DirSelected: receives the directory that was selected by the user.

2. SelectDirectory( Dir, Options, HelpCtx ) shows an additional edit-box above the directory tree. The parameters:

  • Dir: the starting directory.
    If a folder was selected, its name is also found in this variable.
     
  • Options: a set of values. If Options is empty, no additional edit-box is showed and the user can only select an already existing folder. Options may also contain a combination of the following values:
    • sdAllowCreate: an edit box appears, for entering a folder name. Attention: a non-existing folder is only created if Options also contains sdPerformCreate!
    • sdPerformCreate: if the folder does not exist, it is created automatically.
    • sdPrompt: displays a message box that informs the user when the folder does not exist and asks if it should be created. If the user chooses OK, the folder is created.
       
  • HelpCtx: the help context ID number. Only applicable if you programmed a help-system into your application.

In both cases, the function returns TRUE if a folder was selected, otherwise FALSE.

How to use this Delphi function? Two examples, correspondig with the pictures above:

// Syntax 1
procedure TForm1.Button1Click(Sender: TObject);
var
  DirSelected: string;
begin
  if SelectDirectory('Select a folder:', 'D:\Delphi', DirSelected) then
    ShowMessage('You selected ' + DirSelected)
  else
    ShowMessage('You did not select a folder');
end;
// Syntax 2
procedure TForm1.Button2Click(Sender: TObject);
var
  Dir: string;
begin
  Dir := 'D:\Delphi';
  if SelectDirectory(Dir, [sdAllowCreate, sdPerformCreate, sdPrompt], 0) then
    ShowMessage('You selected ' + Dir)
  else
    ShowMessage('You did not select a folder');
end;

IMPORTANT: SelectDirectory only works if you add FileCtrl to the uses-directive near the top of your unit. For example, if it is:
     uses Windows, Messages, ..., StdCtrls;
change it to:
     uses Windows, Messages, ..., StdCtrls, FileCtrl;

 

Crash
Course
Delphi
Become member of the DelphiLand Club and get our Crash Course Delphi, plus the fully commented source code of all our tutorial projects, plus guaranteed answers from our Q/A Forum.
Membership is for life.

TOP :: Source Code and Tutorials :: Crash Course Delphi :: Forum
DelphiLand Club :: :: DC Library :: Tips :: Downloads :: Links

© Copyright 1999-2016 
Studiebureau Festraets