创建TMenuItem运行时时如下所示:
mi := TMenuItem.Create([owner]);
并像这样添加到TPopupMenu:
PopupMenu1.Items.Add(mi);
我是否需要将[owner]
指定为PopupMenu1,还是可以使用nil
?
在这种情况下,PopupMenu1会释放mi
,如果是,我该如何验证呢?
答案 0 :(得分: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以释放弹出窗口。该项目将在销毁时通知您的表单。