2

I want to be able to do Panel1.Update(param), where Panel1 is an object on Form1, and where Update(param) is my method - that I want to add to all the VCL methods this instance of TPanel is born with.

Newbie. It is 25 years since I worked with Delphi. I am struggling with the OO concept, I guess.

no code

Panel1.Update(param);

Erlend
  • 43
  • 6
  • You can use an interposer class for that. See f.i. http://zarko-gajic.iz.hr/delphi-interceptor-classes-tbutton-classtbutton/ – MartynA Jan 20 '19 at 12:16
  • See [Delphi subclass visual component and use it](https://stackoverflow.com/q/14783400/576719) – LU RD Jan 20 '19 at 12:23
  • I was looking for how to code a method for a single _instance_ of e.g. TPanel. From the answers it seems I have to do this to the _class_ - does that means I have to do that - that adding a method to a single instance is not possible? – Erlend Jan 20 '19 at 13:13
  • 1
    Yes, it has to be the class, you can't add a method to an instance. – MartynA Jan 20 '19 at 13:45
  • 1
    That's the [definition](http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Methods_(Delphi)) of a method. – Sertac Akyuz Jan 20 '19 at 13:57
  • Thank you, this clarifies a lot. – Erlend Jan 20 '19 at 19:56

1 Answers1

3

Following is a minimal example of using an interposer class to add a new method to a TPanel.

type
  TPanel = class(ExtCtrls.TPanel)
    protected
    procedure Update(Param : String);
  end;

  TForm1 = class(TForm)
    Panel1: TPanel;
    procedure FormCreate(Sender: TObject);
  public
  end;

[...]

    { TPanel }

procedure TPanel.Update(Param: String);
begin
  Caption := 'ParamValue: ' + Param;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Panel1.Update('abc');
end;

Note that you have to add the method to a class descended from ExtCtrls.TPanel. You cannot add a method to an instance of TPanel, because that's not the way Delphi works, Delphi generates code for the class's methods, not for a specific instance of the class.

Note also that there is nothing to stop you giving the interposer class the same name as the class it descends from (the unit qualifier "ExtCtrls" disambiguates the two).

Note also that the interposer class can be in a separate unit from your form; in that case the interposer class units has to appear in your form's Uses list after ExtCtrls.

MartynA
  • 30,454
  • 4
  • 32
  • 73
  • Thank you, I will give this a try. – Erlend Jan 20 '19 at 19:56
  • 1
    Yes, this has solved my problem. In my opinion though the solution is a bit off the beaten track, so I will instead change my approach to allow a more standard practice, using a procedure to act on the object instead of the object acting on itself. – Erlend Jan 23 '19 at 08:37