Changing component class at run-time on demand

后端 未结 3 2038
误落风尘
误落风尘 2020-12-01 07:17

My Question is similar to the idea here: Replacing a component class in delphi.
But I need to change a specific component(s) class on demand.
Here is some p

3条回答
  •  鱼传尺愫
    2020-12-01 07:24

    This is easier as thought (thanks to Hallvard's Blog - Hack#14: Changing the class of an object at run-time):

    procedure PatchInstanceClass(Instance: TObject; NewClass: TClass);
    type
      PClass = ^TClass;
    begin
      if Assigned(Instance) and Assigned(NewClass)
        and NewClass.InheritsFrom(Instance.ClassType)
        and (NewClass.InstanceSize = Instance.InstanceSize) then
      begin
        PClass(Instance)^ := NewClass;
      end;
    end;
    
    type
      TMyButton = class(TButton)
      public
        procedure Click; override;
      end;
    
    procedure TMyButton.Click;
    begin
      ShowMessage('Click!');
    end;
    
    procedure TForm1.FormCreate(Sender: TObject);
    begin
      PatchInstanceClass(Button1, TMyButton);
    end;
    

提交回复
热议问题