該程序利用DriveCommboBox控件來獲得系統具有的驅動器,並以此作為目錄樹的最上層,利用FileListBox控件,通過設置其Filetype屬性為fdDirectory,可以獲得所需的子目錄,在TreeVIEw控件的OnExpanding事件中將得到的子目錄加到該控件的某一節點下。
整個程序的源代碼如下:
unit main;
interface
uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,StdCtrls, FileCtrl, ComCtrls, ImgList;
type
TForm1 = class(TForm)
DirTreeView: TTreeVIEw;
FileListBox1: TFileListBox;
DriveComboBox1: TDriveComboBox;
ImageList1: TImageList;
procedure FormCreate(Sender: TObject);
procedure DirTreeVIEwExpanding(Sender: TObject; Node: TTreeNode;var AllowExpansion: Boolean);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
var
FirstNode,DirNode : TTreeNode;
ItemCount,Index:integer;
Itemstr:string;
begin
ItemCount:= DriveComboBox1.Items.Count; //所有驅動器的個數
FirstNode := DirTreeVIEw.Items.GetFirstNode;
for index := 0 to ItemCount -1 do
begin
ItemStr:= DriveComboBox1.Items[index];
ItemStr:= copy(ItemStr,1,pos(:,ItemStr)) ; //獲得驅動器的名稱(比如C/D)
DirNode := DirTreeVIEw.Items.AddChild(FirstNode, ItemStr );
DirNode.HasChildren := true;
DirNode.ImageIndex := 0;
DirNode.SelectedIndex := 1;
end;
end;
//響應擴展事件
procedure TForm1.DirTreeVIEwExpanding(Sender: TObject; Node: TTreeNode;Var AllowExpansion: Boolean);
var
DirNode : TTreeNode;
ItemCount,Index,level,icount:integer;
Itemstr,strPath:string;
begin
if node.Count = 0 then
begin
icount:=0;
level:=node.Level ;
dirnode:=node;
strPath:=node.Text+\ ;
while level 0 do
begin
strPath:=dirnode.Parent.Text+\+strpath;
dirnode:=dirnode.parent;
level :=level -1;
end;
FileListBox1.Clear ;
FileListBox1.Directory := strpath;
ItemCount:= FileListBox1.Items.Count;
for index:=0 to ItemCount -1 do
begin
itemstr:=filelistbox1.items[index];
itemstr:= copy(ItemStr,2,pos(],ItemStr)-2) ;
if (itemstr〈〉.) and (itemstr 〈〉 ..) then
begin
DirNode := DirTreeVIEw.Items.AddChild(Node,itemstr );
DirNode.HasChildren :=true;
DirNode.ImageIndex := 0;
DirNode.SelectedIndex := 1;
icount:=icount+1;
end;
if icount = 0 then
Node.HasChildren := false;
end;
end;
end;
end.
程序的運行效果如圖所示:我們可以展開目錄樹中的任何一個節點,並且可以在任意節點之間切換,就象我們在Windows資源管理器中所作的那樣,而不需要逐級回退之後才能進行切換。