2005. november 29., kedd

How to free a component in a message handler


Problem/Question/Abstract:

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:


const
  UM_DELETEOBJECT = WM_USER + 666;
type
  TUMDeleteObject = packed record
    Msg: Cardinal;
    Obj: TObject;
    Unused: Longint;
    Result: Longint;
  end;

  {in form declaration, private section}

procedure UMDeleteObject(var msg: TUMDeleteObject); message UM_DELETEOBJECT;

procedure TaaDEOutputFrm.UMDeleteObject(var msg: TUMDeleteObject);
begin
  msg.Obj.Free;
end;

procedure TaaDEOutputFrm.PanelClick(Sender: TObject);
begin
  if Sender is TPanel then
    PostMessage(handle, UM_DELETEOBJECT, wparam(sender), 0);
end;

Nincsenek megjegyzések:

Megjegyzés küldése