Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 327
Vlad Avatar asked May 16 '12 11:05

Vlad


1 Answers

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.

like image 123
Sertac Akyuz Avatar answered Sep 23 '22 10:09

Sertac Akyuz