Author: Tomas Rutkauskas
I am writing a MDI application. In this application, I just want to create one
instance of the MDI child form. That is, if the user clicks New the first time, a
MDI child form is created, but on subsequent click, no MDI child will be created.
How can I do this and how can I refer to the MDI child that I have created.
Answer:
I assume you know the method to create an instance of a MDIChild form, but I'm
going to go through it just in case:
Create your form, set its formstyle property to fsMDIChild, remove it from the
autocreate list in your Project|Options.
Use the following code to create the form at run-time (I'm using Button1.Click to
create the event):
1 procedure TMainForm.Button1Click(Sender: TObject);
2 var3 MyChildForm: TMDIChild {where TMDIChild is TNameOfYourForm}4 begin5 MyChildForm := TMDIChild.Create(Application);
6 end;
Now, to ensure that only 1 instance of a MDIChild is created change the above code
to read:
7 begin8 if MDIChildCount < 1 then9 MyChildForm := TMDIChild.Create(Application);
10 end;
This code will ensure that only one MDIChild can be open at a given time. Remember
to place Action:=caFree in the OnClose event handler of your MDIChild to free
memory and resources when it's closed.
To access properties of your MDIChild (Even though there's only going to be 1 in
existence) you must use the following type of code (Here an event of the MDIParent
is going to disable a component on the MDIChild):
11 procedure TMainForm.TurnItOffClick(Sender: TObject);
12 begin13 MyChildForm(ActiveMDIChild).Button1.Enabled := False;
14 end;
Now, you didn't state whether you only wanted 1 MDIChild form open in the parent form or only 1 of each particular type. If it's the latter, you'll need to access the classes of all your MDI children to see if an instance already exists.