Adding new methods and properties without registering new components (Views: 101)


Is there a way to add new methods and properties to a component without having its soruce code and having to install a descendant component?


Adding new methods and properties

Sometimes we need to add new methods and properties to an existing component (or change the visibility of existing properties). 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:

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

These methods could for example be implemented this way:

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

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

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;



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 in the InplaceEditor example
explained in the article "Accessing hidden properties".

Copyright (c) 2001 Ernesto De Spirito
Visit: http://www.latiumsoftware.com/delphi-newsletter.php

<< Back to main page