檔案總管右半邊Delphi TListView
延續上一篇 想要寫一個”檔案總管”的想法,今天先來完成”右半邊”。
TListView元件就具備”右半邊”的這些功能:顯示模式(大小圖示、清單、詳細資料)、點擊標頭可排序、Double click可執行或開啟(依系統設定之聯結)。
完成畫面:
環境:Delphi RAD 10.4 Win10 64x
Source+Exe 下載
註:本程式碼,主要參考N多年前的一本Delphi 5 的書。
使用TSearchRec搜尋檔案:
//find the first one
flag := FindFirst(sPath, faAnyFile,sRec);
//if found
if flag=0 then begin
// add into ListView
newItem := ListView1.Items.Add;
newItem.Caption := sRec.Name; // file name
newItem.SubItems.Add(intToStr(sRec.Size)); // size
newItem.SubItems.Add(DateTimeToStr(FileDateToDateTime(sRec.Time))); // time
// is directory
if sRec.Attr = faDirectory then newItem.ImageIndex := 1;
// find next
while (FindNext(sRec)=0) do
begin
// add into ListView
newItem := ListView1.Items.Add;
newItem.Caption := sRec.Name; // file name
newItem.SubItems.Add(intToStr(sRec.Size)); // size
newItem.SubItems.Add(DateTimeToStr(FileDateToDateTime(sRec.Time))); // time
// is directory
if sRec.Attr = faDirectory then newItem.ImageIndex := 1;
// Sort
ListView1.AlphaSort;
end;
FindFirst 找到返回0
SearchRec.Attr faDirectory= 16 faAnyFile=71 faArchive=32
SearchRec 屬性 .Name .Size .Time .TimeStamp .Attr 可取用
元件初始設定:
//--- 設定各元件初始值
procedure TForm1.componentSetUp;
begin
with ListView1 do begin
ColumnClick := True;
Columns[0].Caption := 'NAME';
Columns[1].Caption := 'SIZE';
Columns[2].Caption := 'DATE';
SortType := stBoth;
ViewStyle := vsReport;
PopupMenu := PopupMenu1;
largeImages := ImageList1;
smallImages := ImageList2;
end;
with cmbFilter do begin
FileList := FileListBox1;
Filter := 'All files (*.*)|*.*|Text files (*.txt)|*.txt';
Filter := Filter+ '|BMP (*.bmp)|*.bmp|JPG (*.jpg)|*.jpg';
end;
end;
ListView 功能:
ListView.ColumnClick 內容重新排序
procedure TForm1.ListView1ColumnClick(Sender: TObject; Column: TListColumn);
begin
ListView1.SortType := stNone;
if Column.Index <> SortedColumn then begin
SortedColumn := Column.Index;
Descending := False;
end else Descending := not Descending;
ListView1.SortType := stData;
end;
SortType
If SortType is not stNone, the list items in the Items property are automatically sorted.
ListView1DblClick 執行 ShellExec API
procedure TForm1.ListView1DblClick(Sender: TObject);
var
fTmp,fullPath, fDir,YesNo : string;
flag : Boolean;
begin
fDir := DirectoryListBox1.Directory;
fTmp := ListView1.items[ListView1.ItemIndex].Caption;
fullPath := fDir+'\'+fTmp;
doExec(fullPath);
end;
按右鍵 popupmenu 選擇不同顯示方式
ListView1.ViewStyle vsIcon vsSmallIcon vsList vsReport