A user ("Commodianus") of the About Delphi Programming Forum posted a question Count MDI Children of Class: I have two types of MDI Child forms in my application. How might I go about counting each one? One is TFrmStatus the Other is FrmChannel. How do I know how many TFrmStatus children are alive?.
MDI Child Count By ClassHere's how I do it in my Delphi MDI application...
First a "setup" I use for every MDI application:
1. There's a base class for all MDI child forms (TChildBaseForm). TChildBaseForm's FormStyle property is set to "fsMDIChild.". Here's the skeleton code:
Note that the OnFormClose event is used to set the Action parameter to caFree to properly free the memory occupied by the child form when it closes. If this is left out, the form would only minimize.
Windows, Messages, SysUtils, Variants, Classes,
Graphics, Controls, Forms, Dialogs;
//base class for all MDI child forms
TChildBaseForm = class(TForm)
procedure FormClose(Sender: TObject; var Action: TCloseAction) ;
procedure TChildBaseForm.FormClose(Sender: TObject; var Action: TCloseAction) ;
Action := caFree;
Note also that forms of this class are never instantiated - TChildBaseForm is only used as a base class in visual form inheritance.
2. Every child form that will actually be created inherits from the TChildBaseForm. Here are two such child forms:
TChildImageForm = class(TChildBaseForm)
TChildTreeForm = class(TChildBaseForm)
3. Finally, there's a CreateMDIChild function in the MDI main form's unit that is called when a child needs to be created:
The TChildBaseFormClass is defined as:
function TMainForm.CreateMDIChild(const baseChild : TChildBaseFormClass) : TChildBaseForm;
function CountOf(const childClassName : string) : integer;
cnt : integer;
result := 0;
for cnt := 0 to -1 + MDIChildCount do
if MDIChildren[cnt].ClassName = childClassName then
result := result + 1;
result := baseChild.Create(Application) ;
result.Caption := Format('%s %d', [baseChild.ClassName, CountOf(baseChild.ClassName)]) ;
To actually create an MDI child the next code is used:
TChildBaseFormClass = class of TChildBaseForm;
Note the CountOf(const childClassName : string) sub-function in the CreateMDIChild function. CountOf returns the number of child forms by their class.
//to create a "child image" form
//to create a "child tree" form
I hope this answers the question posted on the Forum :)