发信人: mr_rabbit()
整理人: jchao(1999-09-04 01:15:25), 站内信件
|
在BCB中,TTreeView元件(树状视图)用一种缩进式的树状结构来描绘一组 对象在逻辑上的层次关系,树中的一些结点的左边有一个按钮,可以扩展或折叠 子树,结点还可以有标签以及几副任选的位图。用TtreeView元件来表达文件系统 的目录层次结构是最好不过的了,在WIN95的WINDOWS资源管理器中我们就可以看 到目录结构是用树状视图来表示的。下面给出一个用Borland C++ Builder4 为T TtreeView装载目录树的例子。
1新建一个工程,在Form1上放置一个TtreeView和TButton元件 ,分别命名为Tre eView1和Button1。
2 在Form1的头文件中TForm1类的Public声明函数:
class TForm1 : public TForm
{
__published: // IDE-managed Components
TTreeView *TreeView1;
TButton *Button1;
void __fastcall Button1Click(TObject *Sender);
private: // User declarations
public: // User declarations
__fastcall TForm1(TComponent* Owner);
void __fastcall SetSubNodes(TTreeNode *Node);
};
3在Button1的OnClick事件中放置如下代码:
#include <direct.h> // 目录和路径头文件
.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
int d=3;
TreeView1->Items->Clear();
//寻找可用的盘符
if (_chdrive(1)= =0)
TreeView1->Items->Add(NULL,"A:");
if (_chdrive(2)= =0)
TreeView1->Items->Add(NULL,"B:");
while (_chdrive(d)= =0)
{
TreeView1->Items->Add(NULL,AnsiString(char(64+d))+":");
d++;
}
//为每个盘符装载目录树
int iCount=TreeView1->Items->Count;
for (int i=iCount-1;i>=0;i--)
SetSubNodes(TreeView1->Items->Item[i]);
}
注意:上面不能写成
for (int I=TreeView1->Items->Count-1;I>=0;I--)
SetSubNodes(TreeView1->Items->Item[i]);
因为TtreeView中Count属性是动态变化的,否则出错。
//-------------------------------------------------------------------- ---------------------------------
4 在Form1的源文件输入函数SetSubNodes的代码:
void __fastcall TForm1::SetSubNodes(TTreeNode *Node)
{
int i,iCount,iAttr,done;
AnsiString Path;
TSearchRec sr;
TTreeNode *TempNode;
TempNode=Node;
Path=Node->Text;
while (TempNode->Parent!=NULL)
{
TempNode=TempNode->Parent;
Path=TempNode->Text+"\\"+Path;
}
Path=Path+"\\*.*";
iAttr=faDirectory;
done=FindFirst(Path,iAttr,sr);
if (!done)
{
while (!done)
{
if ((sr.Attr & iAttr)= =iAttr)
if (sr.Name!="." && sr.Name!="..")
TreeView1->Items->AddChild(Node,sr.Name);
done=FindNext(sr);
}
iCount=Node->Count;
for (i=iCount-1;i>=0;i--)
SetSubNodes(Node->Item[i]);
}
FindClose(sr);
}
-- ※ 来源:.月光软件站 http://www.moon-soft.com.[FROM: 202.104.162.35]
|
|