Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use Free instead of Release for modal forms in Delphi?

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?

like image 234
mjn Avatar asked May 27 '09 16:05

mjn


People also ask

What is modal form in Delphi?

Delphi supplies modal forms with the ModalResult property, which we can read to tell how the user exited the form. The following code returns a result, but the calling routine ignores it: var F:TForm2; begin F := TForm2. Create(nil); F. ShowModal; F.

How do I open a new form in Delphi?

To add a form to your project, select either File > New > VCL Form or File > New > Multi-Device Form, according to the type of application you are creating.


1 Answers

Absolutely, and you can also use the FreeAndNil routine. The FreeAndNil routine will only free the object if it is not already nil, and also set it to nil after the free. If you call free directly on an object which has already been freed, you get an Access Violation.

MyForm := TMyForm.Create(nil); 
try 
  MyForm.ShowModal; 
finally 
  FreeAndNil(MyForm); 
end;
like image 81
skamradt Avatar answered Sep 21 '22 15:09

skamradt