Delphi source code

Browse for Folder


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. Like all the other code on DelphiLand, 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;

TOP   DC Library  FAQ 
Crash Course Delphi  Tips  Source Code  Downloads  Links 

© Copyright 1999-2019 
Studiebureau Festraets