Search code examples
batch-filedelphicmdscheduled-tasks

How to make delphi VCL application run from the command line


I've got a VCL application in Delphi 10.2. User should choose a few settings and then press the "Run" button.

Now I want this app to run automatically once a day (using Task Scheduler in Windows) with the settings that the user set up already in the app. So I need a solution to run the "Run" button routine from the command line.

How can I make this app not to open the main form, but to run behind the scenes, using the chosen settings?

As far as I understand, I'm supposed to make another unit that would run some scripts from the main VCL App, would get the settings and would pass them as parameters to a function which will call the "Run" button routine. But here I cannot figure out how can I run this unit instead of the main form when Task Scheduler is running the app and not the user.

Or maybe there is a different solution?

Can anyone help please?


Solution

  • You can use a command-line parameter for the exe and run the application accordingly.

    To read the command line parameter use the function ParamStr (when you only use one command line parameter, you can use ParamStr(1) to read the first and only parameter). When you need to have more command line parameters, then use ParamCount to iterate through all the available parameters.

    Depending on the way you want to run your ‘Run’ code and have your config form shown, you can edit the projects .dpr file to show/create the main form when you run the app in ‘config’ mode and in the other case execute the ‘run’ code.

    program MyProgram;
    
    uses
      Vcl.Forms,
      ConfigFormUnit in 'ConfigFormUnit.pas' {ConfigForm},
      RunCodeUnit in 'RunCodeUnit.pas';
    
    {$R *.res}
    
    begin
      Application.Initialize;
    
      if ParamStr(1) = 'run' then
        ExecuteRunCode
      else begin
        Application.MainFormOnTaskbar := True;
        Application.CreateForm(TConfigForm, ConfigForm);
      end;
    
      Application.Run;
    end.
    

    The routine ExecuteRunCode is a public routine in one of the units, which contains the code you want to run in 'Run' mode. (in the example the unit RunCodeUnit.pas).

    unit RunCodeUnit;
    
    interface
    
      procedure ExecuteRunCode;
    
    implementation
    
    procedure ExecuteRunCode;
    begin
      // Code to run
    end;
    
    end.
    

    Of course, you can create two separate programs, each having its own specific code, but this way you can use a single application if you want/need.