你可以利用TFrame
的WM_DESTROY
處理程序是這樣的:
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Forms, StdCtrls;
type
TFrame1 = class(TFrame)
ComboBox1: TComboBox;
private
procedure WMDestroy(var Msg: TWMDestroy); message WM_DESTROY;
procedure FreeComboBoxItems;
public
constructor Create(AOwner: TComponent); override;
end;
implementation
{$R *.dfm}
constructor TFrame1.Create(AOwner: TComponent);
begin
inherited;
// Add some object items to the ComboBox
ComboBox1.AddItem('a', TButton.Create(nil));
ComboBox1.AddItem('b', TMemoryStream.Create);
ComboBox1.AddItem('c', TList.Create);
end;
procedure TFrame1.WMDestroy(var Msg: TWMDestroy);
begin
// Make sure the TFrame is actually destroying - not recreated
if (csDestroying in ComponentState) then
FreeComboBoxItems;
inherited;
end;
procedure TFrame1.FreeComboBoxItems;
var
I: Integer;
begin
OutputDebugString('TFrame1.FreeComboBoxItems');
with Self.ComboBox1 do
for I := 0 to Items.Count - 1 do
begin
OutputDebugString(PChar(Items.Objects[I].ClassName + '.Free'));
Items.Objects[I].Free;
end;
end;
end.
另一種選擇是CR請爲整個應用程序分配一個基本祖先TAppBaseForm
類和TAppBaseFrame
,並將所有表單作爲TAppBaseForm
和所有的幀作爲TAppBaseFrame
。 這種方式TAppBaseForm
可以通知所有它的子女TAppBaseFrame
所有者窗體在TAppBaseForm.FormDestroy
事件處理程序被銷燬。此時組合框項目仍然有效(如Sertac Akyuz的answer所述)。
我的建議是改變你的設計。沒有擁有這些對象的組合框。讓框架擁有你喜歡的任何容器,例如'TObjectList'。然後你可以在你的框架的析構函數中銷燬那個容器。 –
2013-02-23 18:07:59