I was looking at the Stackoverflow question - Program both as Console and GUI and noted that there wasn't an example for Delphi, so I created the following.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
program TestConsoleGUI;
 
{$APPTYPE GUI}
 
{$R *.res}
 
uses
  System.SysUtils,
  VCL.Forms,
  Winapi.Windows,
  TestUnit in 'TestUnit.pas' {Form1};
 
function AttachConsole(const dwProcessId: THandle): BOOL; stdcall; external kernel32 name 'AttachConsole';
 
var
  bFreeConsole: Boolean;
begin
  if ParamCount = 0 then
  try
    { TODO -oUser -cConsole Main : Insert code here }
    Application.Initialize;
    Application.MainFormOnTaskbar := True;
    Application.CreateForm(TForm1, Form1);
    Application.Run;
  except
    on E: Exception do
      ; // Handle exception here
  end else
  begin
    bFreeConsole := False;
    if ParamStr(1) = '/CONSOLE' then
      bFreeConsole := AttachConsole(THandle(-1)) or AllocConsole;
    try
      WriteLn('Hello world');
    finally
      if bFreeConsole then
        FreeConsole;
    end;
  end;
end.