delphivcldelphi-10.2-tokyodesign-time

How to auto include files when Delphi VCL design time package is put onto the form


I built a wrapper around the TWebBrowser in Delphi. The wrapper aims at implementing multiple web browsers (edge chromium, chrome etc) into a single wrapper that auto detects which browser to use.

After I completed the class I turned said class into a VCL component and loaded it into a design time package. My component includes only two files, the wrapper itself and a utilities class. When I drag my component from the tools palette onto a VCL form the wrapper and the utilities class are not added automatically to the project. This means I have to manually include both the wrapper and the utility into the project.

I was hoping there was a way to automatically include these two files into the project when the wrapper is added to the form. I think I have seen this before with other third party components I have used but my memory may be failing me.

If this is a thing that can be done, my assumption is that it would be in the register section of the VCL component.

procedure Register;
begin
   RegisterComponents('My Wrappers', [TWebBrowserWrapper]);
end;

As that is the code that I believe is run when in design time.


Solution

  • Have your design-time package implement a class that inherits from TSelectionEditor and overrides its virtual RequiresUnits() method, and then register that class for your component using RegisterSelectionEditor(). This way, whenever you place your component onto a Form/Frame/DataModule Designer at design-time, any additional units you report from RequiresUnits() will be added automatically to that unit's uses clause when the unit is saved.

    For example:

    uses
      ..., DesignIntf;
    
    type
      TWebBrowserWrapperSelectionEditor = class(TSelectionEditor)
      public
        procedure RequiresUnits(Proc: TGetStrProc); override;
      end;
    
    procedure TWebBrowserWrapperSelectionEditor.RequiresUnits(Proc: TGetStrProc);
    begin
      inherited RequiresUnits(Proc);
      // call Proc() for each additional unit you want added...
      Proc('MyWrapperUnit');
      Proc('MyUtilityUnit');
    end;
    
    procedure Register;
    begin
      RegisterComponents('My Wrappers', [TWebBrowserWrapper]);
      RegisterSelectionEditor(TWebBrowserWrapper, TWebBrowserWrapperSelectionEditor);
    end;