The Delphi online help says that Release should be used to remove a form from memory. However, in many examples for modal forms I have seen this construct:
MyForm := TMyForm.Create(nil);
try
MyForm.ShowModal;
finally
MyForm.Free;
end;
Is Free a safe way to destroy a modal form? As I can see in the source for ShowModal, Application.HandleMessage will be called until the ModalResult is not 0. Is this the reason why Free can not interfere with pending windows messages?
Yes, it's safe to use Free
after a ShowModal
call.
The cases where you need to use Release
are times when you're in the middle of an event handler (eg, OnClick
), where further processing after the event will have to access the form. In that case, calling Release
instead posts a CM_RELEASE
message which doesn't free the event until the event handler is done and control has returned to the message pump (ProcessMessages
/Application.Run
). ShowModal
doesn't return until the event handler is finished and control makes it back up the stack, so calling Free
afterwards is effectively the same place where the CM_RELEASE
message would be processed otherwise.