| 部件 | 属性 | 属性值 |
| form | name caption | form1 ‘目录浏览’ |
| drivecommbobox | name visible |
drivecommbobox1 false |
| filelistbox | name visible filetype |
filelistbox1 false fddirectory |
| imagelist | name | imagelist1 |
| treeview | name images |
d width="102">dirtreeview
该程序利用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资源管理器中所作的那样,而不需要逐级回退之后才能进行切换。
关注此文的读者还看过: