简体   繁体   English

创建和释放TPopupMenu使用的TMenuItem

[英]Creating and Freeing a TMenuItem used by a TPopupMenu

When creating a TMenuItem runtime as shown below: 创建TMenuItem运行时时,如下所示:

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

and adding to a TPopupMenu like so: 并添加到TPopupMenu,如下所示:

PopupMenu1.Items.Add(mi);

Do I need to specify the [owner] as PopupMenu1 or can I use nil ? 我是否需要将[owner]指定为PopupMenu1或者我可以使用nil吗?

Will mi be free by PopupMenu1 in that case, and if so how can I verify it? mi可自由通过PopupMenu1在这种情况下,如果是这样我怎么能确认吗?

You can specify nil as owner, the parent item will free its own items. 您可以将nil指定为所有者,父项将释放其自己的项。

As for verifying, the easiest is to see the code in TMenuItem.Destroy : 至于验证,最简单的方法是查看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. 按Button1首先将项目添加到弹出菜单。 Then press Button2 to free the Popup . 然后按Button2释放弹出窗口 The item will notify your form when it is being destroyed. 该项目将在销毁时通知您的表单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM