问题
Can I display the result of a loop in the console window in a VCL application for debugging purposes?
回答1:
In Windows, the simplest way to output debug information is to use OutputDebugString()
and then use an application able to receive that output. The event viewer in the Delphi IDE itself is able to receive that input, or you can use the DebugView application from SysInternals to get output on a system that hasn't the IDE installed. AFAIK, GExperts has a similar tool too. That's because a GUI application has not by default a console where to write output, otherwise you have to create one (see Gerry's answer).
One of OutputDebugString()
's advantages is that the application will work without problems even if a call slips into a release build (or is if left there intentionally), but be careful then to not output sensitive information, because they can be read using one of the tools above.
You could also create an ad-hoc form (that is, with a memo control) and route output there.
There are also advanced logging facilities like SmartInspect, CodeSite and others.
回答2:
The simplest way is to compile as a console application, but put the normal application framework code back in the dpr.
program Project2;
{$APPTYPE CONSOLE}
uses
Forms,
SysUtils,
Unit1 in 'Unit1.pas' {Form1};
begin
Application.Initialize;
Application.CreateForm(TForm1, Form1);
writeln('Hello, World!');
Application.Run;
end.
A slightly more complex way is to use the Windows API AllocConsole call:
program Project2;
uses
Forms,
SysUtils,
Windows,
Unit1 in 'Unit1.pas' {Form1};
begin
Application.Initialize;
Application.CreateForm(TForm1, Form1);
AllocConsole;
writeln('Hello, World!');
Application.Run;
end.
This method has the (usually) disadvantage of creating a new console if you are calling from the command line. From memory getting redirection to work requires some more code as well. The advantage is that you can decide to allocate the console at run-time, rather than compile time.
回答3:
Delphi has got an option for this, check "Generate console application" in the linker options for the project. Standard I/O will be directed to a console window which will accompany your GUI application. Then you can use Writeln etc. as you normally would.
Read Output (or Input) from the docs:
Delphi programs have a standard output file if they are linked as console applications.
回答4:
If you wrote the console application, you can try OutputDebugString function in the console application (I didn't try).
Or you can capture the output of the console application like in Capture the output from a DOS (command/console) Window .
Also, you can check Console Application Runner Classes. I use these classes. I think they are great.
来源:https://stackoverflow.com/questions/4421042/how-can-i-write-to-the-console-window-for-debugging