Re: Browse for Folder in Delphi


[ Delphi Forum -- by DelphiLand ]

Posted by webmaster Guido on October 24, 2003

In Reply to: Browse for Folder posted by Johan p14205 on October 23, 2003

: How can i use the Browse for Folder dialog box in my Delphi program to ask the user for a folder?

: Really like the DelphiLand Club!
----------------------

The following function lets the user browse for a folder in a treeview, that starts at the desktop. If a folder is selected, the function returns TRUE and the name of the selected folder is placed in variable Foldr; otherwise, it returns FALSE.

Don't let the code scare you, because it uses some exotic types of variables and the Windows API-function SHBrowseForFolder... just copy it and use it, has been fully tested :)

function BrowseForFolder(var Foldr: string; Title: string): Boolean;
var
  BrowseInfo: TBrowseInfo;
  ItemIDList: PItemIDList;
  DisplayName: array[0..MAX_PATH] of Char;
begin
  Result := False;
  FillChar(BrowseInfo, SizeOf(BrowseInfo), #0);
  with BrowseInfo do begin
    hwndOwner := Application.Handle;
    pszDisplayName := @DisplayName[0];
    lpszTitle := PChar(Title);
    ulFlags := BIF_RETURNONLYFSDIRS;
  end;
  ItemIDList := SHBrowseForFolder(BrowseInfo);
  if Assigned(ItemIDList) then
    if SHGetPathFromIDList(ItemIDList, DisplayName) then begin
      Foldr := DisplayName;
      Result:=True;
    end;
end; 

IMPORTANT: the function above will only work if you add SHLOBJ to the uses-directive in your unit. For example, if it is:
    uses Windows, Messages, SysUtils, ..., StdCtrls;
change it to:
    uses Windows, Messages, SysUtils, ..., StdCtrls, SHLOBJ;

How to use the function? Here's an example: let the user browse for a folder and display it in the label Label1; if no folder was selected, we display "Nothing was selected".

procedure TForm1.Button1Click(Sender: TObject);
var
  Foldr: string;
begin
  if BrowseForFolder(Foldr, 'Select a folder') then 
    Label1.Caption := Foldr
  else 
    Label1.Caption := 'Nothing was selected';
end;