2

When writing a Lazarus program, you have the option of using $APPTYPE console or deselecting the Win32 GUI Application (-WG option) in the Project Options .

I noticed that without these options DebugLn and WriteLn raise exceptions. Is there a way to create a console even if the program is not compiled above mentioned options and output to it with DebugLn and WriteLn afterwards?

Kara
  • 6,115
  • 16
  • 50
  • 57
vfclists
  • 19,193
  • 21
  • 73
  • 92
  • 1
    I don'tknow about freepascal or lazarus, but the AllocConsole win32 api function can do it in C and D... http://msdn.microsoft.com/en-us/library/windows/desktop/ms681944%28v=vs.85%29.aspx – Adam D. Ruppe Nov 22 '13 at 00:10
  • [FreePascal and Lazarus][1] I want to know if it is implemented in the libraries on supported platforms [1]: http://www.lazarus.freepascal.org/ – vfclists Nov 22 '13 at 00:17
  • 1
    http://stackoverflow.com/q/4421042/62576 explains how it can be done with Delphi and the VCL. If you're targeting other platforms than Win32, it probably won't help, though. It's doubtful this is possible for all platforms supported by FreePascal/Lazarus, IMO. – Ken White Nov 22 '13 at 00:19

2 Answers2

8

In windows it is a little more tricky compared to Delphi. In Delphi all you need to do is to call AllocConsole. Using Lazarus/FreePascal you need to do a little extra work:

uses
  Windows;
begin
  AllocConsole;      // in Windows unit
  IsConsole := True; // in System unit
  SysInitStdIO;      // in System unit
  // Now you can do Writeln, DebugLn, ...
end.

Unfortunately I cannot help you on other platforms. Although iirc in linux console is always present for a program even if not visible. So it should work without extra code. However I cannot test this atm so take it with a grain of salt.

Avo Muromägi
  • 1,563
  • 1
  • 12
  • 21
  • Afaik daemons have no stdin/out, closing them is part of the daemonization process. The classic way of reopening stdout is simply doing rewrite(output); similarly reset for stdin. – Marco van de Voort Nov 22 '13 at 20:17
2

Well, obviously setting project as gui application rather then program is much better for programming. All needed uses clauses are alredy present.

So that kind of problem, getting power of lazarus, but working as console application I solve with adding Application.ShowMainForm:=False; before

Application.CreateForm(TForm1, Form1);

in .lpr file.

Everything works fine, even showmessage (everything) can be used.

josifoski
  • 1,696
  • 1
  • 14
  • 19
  • Does that mean that a console program treats the console as the main form, thus suppressing it with `Application.ShowMainForm := False`? If that is the case how can the console be displayed afterwards? – vfclists Nov 23 '13 at 15:07