測試效果圖:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ExtCtrls;
type
TForm1 = class(TForm)
TreeView1: TTreeVIEw;
Panel1: TPanel;
Edit1: TEdit;
Button1: TButton;
procedure Button1Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{函數的默認參數是指定顯示在第幾個元素下面}
function DirToTree(Tree: TTreeVIEw; Path: string; num: Integer = -1): Boolean;
var
sr: TSearchRec;
node: TTreeNode;
begin
path := ExcludeTrailingPathDelimiter(path); {去掉最後一個 '\'}
if not DirectoryExists(path) then Exit; {路徑不存在則退出}
if num = -1 then node := nil else node := Tree.Items[num]; {確認節點}
if FindFirst(Path + '\*.*', faAnyFile, sr) = 0 then
begin
repeat
if sr.Name[1] = '.' then Continue; {如果是'.' 或 '..' (當前目錄或上層目錄)則忽略}
Tree.Items.AddChild(node, sr.Name); {都是通過這句添加的}
Application.ProcessMessages; {加上可以讓程序兼顧其他消息}
{如果是文件夾則執行遞歸}
if (sr.Attr and faDirectory) = faDirectory then
DirToTree(Tree, Path + '\' + sr.Name, Tree.Items.Count-1);
until (FindNext(sr) <> 0);
end;
Result := True;
end;
{測試}
procedure TForm1.Button1Click(Sender: TObject);
begin
TreeVIEw1.Items.Clear;
DirToTree(TreeVIEw1, Edit1.Text);
end;
end.