Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cleanly free a frame within a click event on a button on the frame?

Tags:

delphi

I used to able to do this using plain delphi buttons:

In the First Frame I have (simplified)

procedure FirstFrame.ButtonClick(Sender: TObject)
Begin
  if TButton(Sender).ModalResult = mrOK then
    ChildFrame.DoOKStuff
  else
    ChildFrame.DoCancelStuff;
  ChildFrame.Free;
end;

procedure FirstFrame.ShowFranme;
begin
  ChildFrame := TFrameWithButtons.Create(Owner);
  ChildFrame.Parent := self;
  ChildFrame.OKButton.OnClick := ButtonClick;
  ChildFrame.CancelButton.OnClick := ButtonClick;
  ChildFrame.Visible := True;
end;

In the Childframe I do nothing to process the button click... the button click is already set to return control to the First Frame.

With some third Party buttons this occasionally causes an AV. I understand why - at some point in the 3rd party code processing returns to a now freed frame or button BUT the called code is in the first frame... Annoyingly it just works 99.99% of the time :)

There is no Release procedure for frames.

So my question is what is the correct way to handle this situation?

Using both Delphi 6 and Delphi 2009.

like image 652
Despatcher Avatar asked Dec 28 '22 17:12

Despatcher


1 Answers

Try this:

type
  TFrameWithButtons = class(TFrame)
    ...
    procedure CMRelease(var Message: TMessage); message CM_RELEASE;
    ...
  end;

procedure TFrameWithButtons.CMRelease(var Message: TMessage);
begin
  Free;
end;

procedure FirstFrame.ButtonClick(Sender: TObject)
Begin
  if TButton(Sender).ModalResult = mrOK then
    ChildFrame.DoOKStuff
  else
    ChildFrame.DoCancelStuff;
  PostMessage(ChildFrame.Handle, CM_RELEASE, 0, 0);
end; 
like image 90
Remy Lebeau Avatar answered Mar 16 '23 00:03

Remy Lebeau