子菜单随便有多少层都可以。我还没想到如何为每个结点添加事件。
Procedure TfrmMenuTree.Button1Click(Sender:TObject);
//内嵌过程,也可以写到外面去
Procedure AddItem(ANode:TTreeNode; menuItem:TMenuItem);
Var
j, k:Integer;
NewNode:TTreeNode;
Begin
k := menuItem.Count;
For j := 0 To k - 1 Do
Begin
//在哪个结点下添加菜单
NewNode := tv.Items.AddChild(ANode, menuItem.Items[j].Caption);
//如果此菜单有子菜单.........
If menuItem.Items[j].Count > 0 Then
AddItem(NewNode, menuItem.Items[j]);
End;
End;
//----------------------------------------
Var
i:Integer;
Node:TTreeNode;
Begin
tv.Items.Clear; //tv是TreeView控件
tv.Items.BeginUpdate;
For i := 0 To MainMenu.Items.Count - 1 Do //MainMenu是form上的一个菜单
Begin
//在TreeView根下添加第一层
Node := tv.Items.Add(Nil, MainMenu.Items.Caption);
//然后处理N层菜单
If MainMenu.Items.Count > 0 Then
AddItem(Node, MainMenu.Items);
End;
tv.Items.EndUpdate;
End;
------------------------------------------------
那个内嵌过程写到外面好看一点
//内嵌过程,也可以写到外面去
Procedure TfrmMenuTree.AddItem(ANode:TTreeNode; menuItem:TMenuItem);
Var
j, k:Integer;
NewNode:TTreeNode;
Begin
k := menuItem.Count;
For j := 0 To k - 1 Do
Begin
//在哪个结点下添加菜单
NewNode := tv.Items.AddChild(ANode, menuItem.Items[j].Caption);
//如果此菜单有子菜单.........
If menuItem.Items[j].Count > 0 Then
AddItem(NewNode, menuItem.Items[j]);
End;
End;