TMenuItemInsert (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This code inserts a menu item after the first item in a menu named FileMenu.

Code

procedure TForm1.InsertMenuItemClick(Sender: TObject);
var
  NewItem: TMenuItem;
begin
  NewItem := TMenuItem.Create(FileMenu);
  try
    NewItem.Caption := 'Do this';
    FileMenu.Insert(1, NewItem);
  except
    NewItem.Free; // Throw away the menu item if there is an error.
    raise; // Raise the exception again.
  end;
  // Do not free the menu item on success. Need it for the menu.
end;

// Free all the menu items that we have created dynamically.
procedure TForm1.FormDestroy(Sender: TObject);
var
  I : Integer;
begin
  for I := FileMenu.Count - 1 downto 0 do  // Index backwards because Count changes as you remove items.
    if FileMenu.Items[I].Name = '' then  // Items created dynamically have no name.
      FileMenu.Items[I].Free;
end;

Uses