unit TMenuItemInsert;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Menus, StdCtrls;

type
  TForm1 = class(TForm)
    MainMenu1: TMainMenu;
    FileMenu: TMenuItem;
    Edit1: TMenuItem;
    Options1: TMenuItem;
    InsertMenuItem: TButton;
    FileSub11: TMenuItem;
    FileSub21: TMenuItem;
    FileSub31: TMenuItem;
    procedure InsertMenuItemClick(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

// BeginExample: TMenuItemInsert
// Method: Menus.TMenuItem.Insert

// BeginCode
{
This code inserts a menu item after the first item in a menu
named FileMenu:
} 
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; // reraise the exception
  end;
  // Don't 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 not name.
      FileMenu.Items[I].Free;
end;
// EndCode
// EndExample: TMenuItemInsert
end.
