Vlad
Vlad

Reputation: 1433

Creating and Freeing a TMenuItem used by a TPopupMenu

When creating a TMenuItem runtime as shown below:

mi := TMenuItem.Create([owner]);

and adding to a TPopupMenu like so:

PopupMenu1.Items.Add(mi);

Do I need to specify the [owner] as PopupMenu1 or can I use nil?

Will mi be free by PopupMenu1 in that case, and if so how can I verify it?

Upvotes: 7

Views: 1420

Answers (1)

Sertac Akyuz
Sertac Akyuz

Reputation: 54832

You can specify nil as owner, the parent item will free its own items.

As for verifying, the easiest is to see the code in TMenuItem.Destroy:

destructor TMenuItem.Destroy;
begin
  ..
  while Count > 0 do Items[0].Free;  
  ..
end;


If that's not enough, to see it in action you can use the notification mechanism:

type
  TForm1 = class(TForm)
    PopupMenu1: TPopupMenu;
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    mi: TMenuItem;
  protected
    procedure Notification(AComponent: TComponent; Operation: TOperation);
      override;
  end;

  ..

procedure TForm1.Button1Click(Sender: TObject);
begin
  mi := TMenuItem.Create(nil);
  mi.FreeNotification(Self);
  PopupMenu1.Items.Add(mi);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  PopupMenu1.Free;
end;

procedure TForm1.Notification(AComponent: TComponent; Operation: TOperation);
begin
  inherited;
  if (AComponent = mi) and (Operation = opRemove) then
    ShowMessage('mi freed');
end;

Press Button1 to first add the item to the popup menu. Then press Button2 to free the Popup. The item will notify your form when it is being destroyed.

Upvotes: 11

Related Questions