You are in the Delphi IDE and need to make a new form. It looks like another form you already have, but not quite. You could copy and tweak it. That’s the quick way to get the result you need. That’s the way most of your predecessors have gone about creating new forms. You know, because every time you change something in one form, a seemingly endless stream of “this one too” requests starts flowing your way. And you suspect, or actually you know, that there will be another request for a similar form quite soon.
Wouldn’t it be great if you could change them all in one place and be done with it?
Well you can.
Delphi supports visual form inheritance. That’s not just inheriting from another form’s class, but also inheriting from its layout, its controls and the way they have been wired together, including the ability to “override” individual settings and adding controls just for the descendant form you are working on.
For new forms visual form inheritance is just a matter of adding a new form to your project through [File | New | Other], navigating to [Inheritable items] and selecting the form that you want to use as the ancestor for your new form.
“All well and dandy, but what about existing forms?”, you ask.
That’s slightly more complicated, but only slightly.
- You start by adding a new form that will become your application’s “master form”. Do this in the normal way you would add a form: [File | New | Form – Delphi]. Let’s name this form [BaseForm] and save it as [BaseForm_Form.pas].
- Add any stuff that you want all your application’s forms to share, controls, other components such as image lists, event handlers, whatever you like.
- Open one of your existing forms and show its
.pasfile. (Hint: use PF12.)
BaseFormto the uses clause.
TForm3 = class(TForm)to
TForm3 = class(TBaseForm). Of course here
TBaseFormis the class name of the BaseForm form you just created and
TForm3stands for the class name of your form.
- Go back to the visual representation of your form. (Hint: use PF12.) You won’t see any of the stuff you added to your BaseForm yet.
- Right click anywhere on the form’s surface and click [View as Text].
- Notice the first word in the textual representation of your form. It is
- Change that from
inheritedso the first line becomes
inherited Form3: TForm3.
- Right click anywhere in the form’s textual representation and click [View as Form].
And hey presto! Your form shows the stuff that is on your BaseForm. Now all you need to do is clean up the form so its own controls do not cover any of the BaseForm’s stuff and add an
inherited; call to all the event handlers that are implemented both in [BaseForm] and your form that is now inheriting from it.