2005. október 5., szerda

How to create only one instance of a MDI child form (2)


Problem/Question/Abstract:

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):


procedure TMainForm.Button1Click(Sender: TObject);
var
  MyChildForm: TMDIChild {where TMDIChild is TNameOfYourForm}
begin
  MyChildForm := TMDIChild.Create(Application);
end;


Now, to ensure that only 1 instance of a MDIChild is created change the above code to read:


begin
  if MDIChildCount < 1 then
    MyChildForm := TMDIChild.Create(Application);
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):


procedure TMainForm.TurnItOffClick(Sender: TObject);
begin
  MyChildForm(ActiveMDIChild).Button1.Enabled := False;
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.

Nincsenek megjegyzések:

Megjegyzés küldése