VCL Delphi

Title: A Better Way to Create Menu Items
Question: How to use the Add method of the popupmenu items property to
easely create a menu at runtime.
Answer:
Have you ever had to construct a menu dynamically at runtime?
If so, you may have code in your project that looks something like this#
PopupMenu1 := TPopupMenu.Create(Self);
Item := TMenuItem.Create(PopupMenu1);
Item.Caption := 'First Menu';
Item.OnClick := MenuItem1Click;
PopupMenu1.Items.Add(Item);
Item := TMenuItem.Create(PopupMenu1);
Item.Caption := 'Second Menu';
Item.OnClick := MenuItem2Click;
PopupMenu1.Items.Add(Item);
Item := TMenuItem.Create(PopupMenu1);
Item.Caption := 'Third Menu';
Item.OnClick := MenuItem3Click;
PopupMenu1.Items.Add(Item);
Item := TMenuItem.Create(PopupMenu1);
Item.Caption := '-';
PopupMenu1.Items.Add(Item);
Item := TMenuItem.Create(PopupMenu1);
Item.Caption := 'Fourth Menu';
Item.OnClick := MenuItem4Click;
PopupMenu1.Items.Add(Item);
There is a faster way! Use the NewItem and NewLine functions to create them all
in one pass like this:
PopupMenu1 := TPopupMenu.Create(Self);
with PopUpMenu1.Items do
begin
Add(NewItem('First Menu',0,False,True,MenuItem1Click,0,'MenuItem1'));
Add(NewItem('Second Menu',0,False,True,MenuItem2Click,0,'MenuItem2'));
Add(NewItem('Third Menu',0,False,True,MenuItem3Click,0,'MenuItem3'));
Add(NewLine); // Adds a separator bar
Add(NewItem('Fourth Menu',0,False,True,MenuItem4Click,0,'MenuItem4'));
end;