7

创建 TMenuItem 运行时时如下所示:

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

并像这样添加到 TPopupMenu 中:

PopupMenu1.Items.Add(mi);

我需要指定[owner]为 PopupMenu1 还是可以使用nil

在这种情况下,PopupMenu1将mi是免费的,如果是这样,我该如何验证它?

4

1 回答 1

11

您可以将 nil 指定为所有者,父项将释放自己的项。

至于验证,最简单的方法是查看以下代码TMenuItem.Destroy

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


如果这还不够,要查看它的实际效果,您可以使用通知机制:

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;

按 Button1 首先将项目添加到弹出菜单。然后按 Button2 释放Popup。该项目将在销毁时通知您的表单。

于 2012-05-16T11:44:57.260 回答