How to cleanly free a frame within a click event on a button on the frame?
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 Fi开发者_如何学运维rst 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.
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;
Take a look at how TCustomForm.Release
is implemented. It's pretty simple: it posts a message to the Windows message queue, which when processed causes the form to free itself. That shouldn't be too difficult to implement in your own code.
精彩评论