Using ShellAPI
unit and few lines of code, we can load directory structure into ListView
and show associated icons and information for each file.
First of all, add ShellAPI
unit to uses list. Place ListView
and ImageList
on form. Into ImageList component, we will store icons for each file.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ImgList, StdCtrls, ComCtrls, ShellAPI;
type
TForm1 = class(TForm)
ListView1: TListView;
Button1: TButton;
ImageList1: TImageList;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
const
sPath = 'c:windows';
var
i: integer;
Icon: TIcon;
SearchRec: TSearchRec;
ListItem: TListItem;
FileInfo: SHFILEINFO;
begin
ListView1.SmallImages := ImageList1;
ListView1.ViewStyle := vsReport;
ListView1.Columns.Add;
ListView1.Columns.Add;
Icon := TIcon.Create;
try
ListView1.Items.BeginUpdate;
i := FindFirst(sPath + '*.*', faAnyFile, SearchRec);
while i = 0 do
begin
application.ProcessMessages;
with ListView1 do
begin
if ((SearchRec.Attr and FaDirectory <> FaDirectory) and (SearchRec.Attr and FaVolumeId <> FaVolumeID)) then
begin
ListItem := ListView1.Items.add;
SHGetFileInfo(PChar(sPath + SearchRec.Name), 0, FileInfo, SizeOf(FileInfo), SHGFI_DISPLAYNAME);
Listitem.Caption := FileInfo.szDisplayName;
SHGetFileInfo(PChar(sPath + SearchRec.Name), 0, FileInfo, SizeOf(FileInfo), SHGFI_TYPENAME);
ListItem.SubItems.Add(FileInfo.szTypeName);
SHGetFileInfo(PChar(sPath + SearchRec.Name), 0, FileInfo, SizeOf(FileInfo), SHGFI_ICON);
Icon.Handle := FileInfo.hIcon;
ListItem.ImageIndex := ImageList1.AddIcon(Icon);
end;
end;
i := FindNext(SearchRec);
end;
finally
ListView1.items.EndUpdate;
Icon.Free;
end;
end;
end.
In sPath constant is a path to directory we will load into ListView. Of course, you can change this dynamically, this is just for example. ListView will be set to Report style automatically and all files in specified directory will be loaded into it together with icon and description.