Easiest way? Put all your code inside a procedure/function and call it from the main program (the .lpr file). For example, supposing you put all that code in a procedure called
MoreSetup in Unit2, your main program might look like:
program project1;
{$mode objfpc}{$H+}
uses
Interfaces, // this includes the LCL widgetset
Forms, Unit1, Unit2;
{$R *.res}
begin
RequireDerivedFormResource:=True;
Application.Scaled:=True;
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Unit2.MoreSetup();
Application.Run;
end.
The form will not show up or give any other sign of life unitl the call to
Application.Run, but it will exist and be (mostly) initialized before the call to
MoreSetUp (and yes, I just tested it
)
The way you're doing it now, your code is being run
before almost any other code in the application, including the initialization of some RTL/FCL/LCL units. Unless absolutely needed it's better to set your code in some kind of "setup" or whatever procedure/function and call it from the main program (or any other unit): It even can be the very first line, if needed.