How to make your forms behave consistently without repeating yourself

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.

  1. 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].
  2. 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.
  3. Open one of your existing forms and show its .pas file. (Hint: use PF12.)
  4. Add BaseForm to the uses clause.
  5. Change TForm3 = class(TForm) to TForm3 = class(TBaseForm). Of course here TBaseForm is the class name of the BaseForm form you just created and TForm3 stands for the class name of your form.
  6. 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.
  7. Right click anywhere on the form’s surface and click [View as Text].
  8. Notice the first word in the textual representation of your form. It is object.
  9. Change that from object to inherited so the first line becomes inherited Form3: TForm3.
  10. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *


Show Buttons
Hide Buttons