Author: Erwin Molendijk
Manage MDI forms. Each form will be visble only once. Form will be created if
needed.
Answer:
1 {2 3 This article describes a base class for your mainform.4 (You can inherite from this form or use it as is)5 6 Three new routines are presented. They will enable you to easily7 manage MDI forms:8 - Only one instance per MDI Class will be activated9 - Creation of MDI class will be handled by routines if needed10 - Activated MDI class will be focused if needed11 12 }13 14 type15 TMDIClass = classof TForm;
16 17 type18 TBaseMainForm = class(TForm)
19 {... }20 public21 { Public declarations }22 function ActivateMDIClass(MDIClass: TMDIClass): TForm;
23 function GetMDIClassIndex(MDIClass: TMDIClass): Integer;
24 function MDIClassIsActive(MDIClass: TMDIClass): Boolean;
25 { ... }26 end;
27 28 implementation29 30 {31 Use ActivateMDIClass() to activate a mdi child class.32 If the class is not created yet, it will be.33 The mdi child will be shown on screen and focused.34 }35 36 function TBaseMainForm.ActivateMDIClass(MDIClass: TMDIClass): TForm;
37 var38 i: Integer;
39 40 begin41 // Try to find index of MDIClass form in MDI child list42 i := GetMDIClassIndex(MDIClass);
43 44 // if index is not found (-1) then create the form45 if i = -1 then46 Result := MDIClass.Create(Application)
47 else48 Result := MDIChildren[i];
49 50 // bring it to front51 Result.Show;
52 Result.BringToFront;
53 end;
54 55 {56 Get mdi child index of specified MDIClass.57 Returns -1 if the MDIClass does not exist as a created MDI form58 }59 60 function TBaseMainForm.GetMDIClassIndex(
61 MDIClass: TMDIClass): Integer;
62 var63 i: Integer;
64 begin65 // Default index -1 = MDIClass not found66 Result := -1;
67 68 // try to find a MDI child of correct MDIClass class69 for i := 0 to MDIChildCount - 1 do70 if MDIChildren[i].ClassType = MDIClass then71 Result := i;
72 end;
73 74 {75 Returns true is the MDIClass exists as a created MDI form76 }77 78 function TBaseMainForm.MDIClassIsActive(
79 MDIClass: TMDIClass): Boolean;
80 begin81 Result := GetMDIClassIndex(MDIClass) <> -1;
82 end;
Usage Example
Create a mainform, inherited from TBaseMainForm.
Create two mdi forms called TfrmBrainstorm and TfrmReport.
Make sure ...FormStyle=fsMDIChild.
Make sure MDI childs can be closed:
83 procedure...FormClose(Sender: TObject;
84 var Action: TCloseAction);
85 begin86 Action := caFree;
87 end;
88 89 Now use the following code to activate those mdi forms:
90 91 procedure TMainForm.OnClick1(Sender: TObject);
92 begin93 ActivateMDIClass(TfrmBrainstorm);
94 end;
95 96 procedure TMainForm.OnClick2(Sender: TObject);
97 begin98 ActivateMDIClass(TfrmReport);
99 end;