Help & Manual authoring tool
Visual components can sometimes be extended with new methods and properties without having to register a new descendant component in the Components Palette

Adding new methods and properties without registering new components

Copyright © 2000 Ernesto De Spirito

SMImport - Native VCL components for importing data

Adding new methods and properties

Sometimes we need to add new methods and properties to an existing component. One way of doing this is modifiying the component, but this implies having to recompile its package and we would have to redistribute our changes if we wanted our application to be compiled by others, and that would be a bother for the recipients. Sometimes we may not even have that choice because we may not have the source code.

In these situations, better would be to subclass (derive) the component and add new properties and methods. For example:

type
TEditX = class(TEdit)
public
  function GetForeColor: TColor;
  procedure SetForeColor(color: TColor);
  property ForeColor: TColor read GetForeColor write SetForeColor;
end;

These methods could be implemented this way:

function TEditX.GetForeColor: TColor;
begin
  Result := Font.Color;
end;

procedure TEditX.SetForeColor(color: TColor);
begin
  Font.Color := Color;
end;

It's a silly example, of course, but it serves the purpose.

Casting to the new class

We don't need to intall this new component and register it in the Components Palette or replace existing controls in our applications (which would be an unpayable penalty for such small changes and/or additions). Instead, any time we want to access the new properties and methods, we can just cast the object (for example Edit1) to our new class. For example:

  TEditX(Edit1).ForeColor := clRed;

or

  TEditX(Edit1).SetForeColor(clRed);

Warning: This casting to a descendant class can only be done if the new class adds new properties and static methods, but without adding new fields and new virtual or dynamic methods, although in theory you can override existing virtual methods. Also, the visibility of existing properties can be changed, as explained in another article.

JfControls Library - for Delphi and C++ Builder
Copyright © 2000/2006 Ernesto De Spirito.   All rights reserved.