关于TreeView的使用,还可以参看:联合使用TreeView 组件 TreeView是一个显示树型结构的控件,通过它能够方便地管理和显示具有层次结构的信息,是Windows应用程序的基本控件之一。DELPHI虽然具有比较强大的文件管理功能,提供了多个用于文件管理的标准控件,如DriveComboBox、DirectoryListBox、FileListBox等,通过设置它们的属性,使其建立起联系,甚至不用编写一行程序,我们就可以实现在不同的目录之间进行切换,然而这样的目录切换只适用于进行文件的查找定位,而不能方便地进行目录的浏览,例如我们要从c:\windows目录转到c:\program files目录,就必须返回到根目录才能进行切换,而不能象Windows资源管理器那样任意地在不同的目录之间进行浏览与切换。
要实现在不同目录之间任意切换和浏览,还是需要使用TreeView控件,以下程序就利用DELPHI的TreeView控件来建立目录树。
在该程序中采用的各部件以及界面设计如下图所示:
 各部件的主要属性设置如下:
| 部件 |
属性 |
属性值 |
| 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 imagelist1
该程序利用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资源管理器中所作的那样,而不需要逐级回退之后才能进行切换。
|