Author: Tomas Rutkauskas
Is it possible to free a component inside its own event handler?
Answer:
Not safely. You never know what the code after your free statement will still try
to do with the (now invalid) self reference.
Do it the way forms implement the Release method: post a user message to the form,
passing the control to delete as parameter, then free the control in the message
handler:
1 const2 UM_DELETEOBJECT = WM_USER + 666;
3 type4 TUMDeleteObject = packedrecord5 Msg: Cardinal;
6 Obj: TObject;
7 Unused: Longint;
8 Result: Longint;
9 end;
10 11 {in form declaration, private section}12 13 procedure UMDeleteObject(var msg: TUMDeleteObject); message UM_DELETEOBJECT;
14 15 procedure TaaDEOutputFrm.UMDeleteObject(var msg: TUMDeleteObject);
16 begin17 msg.Obj.Free;
18 end;
19 20 procedure TaaDEOutputFrm.PanelClick(Sender: TObject);
21 begin22 if Sender is TPanel then23 PostMessage(handle, UM_DELETEOBJECT, wparam(sender), 0);
24 end;