There's no problem with your understanding of a recursive call, but you don't want to append an item for the root node, so you should add an item and recurse for each child of any node that's passed to the procedure. Here's one sample implementation:
type
TForm1 = class(TForm)
..
private
procedure TreeViewToMenu(BaseNode: TTreeNode; OutMenu: TComponent);
..
procedure TForm1.TreeViewToMenu(BaseNode: TTreeNode; OutMenu: TComponent);
var
i: Integer;
Node: TTreeNode;
MenuItem: TMenuItem;
begin
for i := 0 to BaseNode.Count - 1 do begin
Node := BaseNode.Item[i];
MenuItem := TMenuItem.Create(nil);
MenuItem.Caption := Node.Text;
MenuItem.ImageIndex := Node.ImageIndex;
MenuItem.Tag := i;
if Node.Count = 0 then
MenuItem.OnClick := MyMenuItemClick;
if OutMenu is TPopupMenu then
TMenu(OutMenu).Items.Add(MenuItem)
else if
OutMenu is TMenuItem then
TMenuItem(OutMenu).Add(MenuItem)
else
raise Exception.Create('Invalid class type');
TreeViewToMenu(Node, MenuItem);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
..
begin
..
TreeViewToMenu(TreeView1.Items[0], PopupMenu1);
..
Note that I changed the declaration of TreeViewToMenu
for (1) the TreeView is not used and (2) we are appending to items to either a TPopupMenu
or a TMenuItem
, hence I declared 'OutMenu' as TComponent
which would accept both.