2006. szeptember 15., péntek

How to create a submenu at runtime


Problem/Question/Abstract:

I have a menu item in a menu and would like to fill a submenu with items loaded at runtime.

Answer:

procedure TForm1.Button1Click(Sender: TObject);
var
  aItem, aSubItem: TMenuItem;
  i, j: integer;
begin
  with MenuItem1 do {is an existing MenuItem}
  begin
    for i := 0 to 5 do
    begin
      aItem := TMenuItem.Create(MainMenu1);
      Add(aItem);
      aItem.Caption := IntToStr(i);
      for j := 0 to 5 do
      begin
        aSubItem := TMenuItem.Create(MainMenu1);
        aItem.Add(aSubItem);
        aSubItem.Caption := IntToStr(j);
        aSubItem.OnClick := MenuItemsHandler;
      end;
    end;
  end;
end;

procedure TForm1.MenuItemsHandler(Sender: TObject);
begin
  ShowMessage((Sender as TMenuItem).Caption);
end;

Nincsenek megjegyzések:

Megjegyzés küldése