Mirror

How to attach a popup menu to a TMenuItem at runtime (Views: 9)


Problem/Question/Abstract:

How do you attach a popup menu to the TMenuItem of a main menu as a submenu at runtime?

Answer:

This is one way to do it. Note: The PopupMenuItems are added to an existing menu item of the mainmenu mnuWhatEver.

{ ... }
var
  I: integer;
  MenuItem: TMenuItem;
begin
  for I := 0 to PopupMenu1.Items.Count - 1 do
  begin
    with PopupMenu1.Items[I] do
      MenuItem := NewItem(Caption, ShortCut, Checked, Enabled, OnClick, HelpContext,
        Name);
    mnuWhatEver.Add(MenuItem);
  end;
end;

Note: when using NewItem the MenuItem has no owner you'll have to free them yourself when you're done with it.

You could also use:

MenuItem := TMenuItem.Create(Self);

and then copy all the properties yourself.

MenuItem.Captions := PopupMenu1.Items[I].Caption;
MenuItem.OnClick := PopupMenu1.Items[I].OnClick;
{etc.}

<< Back to main page