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
Freeafter aShowModalcall.The cases where you need to use
Releaseare 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, callingReleaseinstead posts aCM_RELEASEmessage which doesn’t free the event until the event handler is done and control has returned to the message pump (ProcessMessages/Application.Run).ShowModaldoesn’t return until the event handler is finished and control makes it back up the stack, so callingFreeafterwards is effectively the same place where theCM_RELEASEmessage would be processed otherwise.