Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over main menu's items (including subitems)

I'm trying to iterate over all main menu's items. Problem starts at sub menus items. Structure like Menu.Items[i].Items[j].Items[k] doesnt look easy to operate on. Is there any method for that?


My goal is to list all the items captions.

like image 814
Jacek Kwiecień Avatar asked Mar 19 '12 13:03

Jacek Kwiecień


2 Answers

You can use a recursive function like so

procedure TForm1.ProcessMenu(AMenu: TMenuItem);
var
  i: integer;
begin
  for i := 0 to AMenu.Count - 1 do
  begin
    Memo1.Lines.Add(AMenu[i].Caption);
    ProcessMenu(AMenu[i]);
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  ProcessMenu(MainMenu1.Items);
end;
like image 164
RRUZ Avatar answered Sep 22 '22 11:09

RRUZ


Use this code:

USES Menus;

TYPE TItemArr = ARRAY OF TMenuItem;

FUNCTION AllItems(MainMenu : TMainMenu) : TItemArr;
  VAR
    I : Cardinal;

  PROCEDURE Parse(VAR Result : TItemArr ; Item : TMenuItem);
    VAR
      I : Cardinal;

    BEGIN
      SetLength(Result,SUCC(LENGTH(Result)));
      Result[HIGH(Result)]:=Item;
      FOR I:=1 TO Item.Count DO Parse(Result,Item.Items[PRED(I)])
    END;

  BEGIN
    SetLength(Result,0);
    FOR I:=1 TO MainMenu.Items.Count DO Parse(Result,MainMenu.Items[PRED(I)])
  END;

Use it as:

VAR MI : TMenuItem;
FOR MI IN AllItems(MainMenu) DO ProcessMenuItem(MI);
like image 24
HeartWare Avatar answered Sep 19 '22 11:09

HeartWare