How to determine if I am running as a console application? (Delphi on Win32)

I have a generic block that does some writing to the GExperts Debugger and / or OutputDebugString. I am going to use it in a console application, so I want it to be able to output to stdout via writeln() .
The main executable already has {$ APPTYPE CONSOLE}, but I donโ€™t think it will help me here. The logging procedure will be called from several places:

  • The main console application that will reference the BPL
  • from another BPL that "requires" the first bpl, and .....
  • from a dll that statically links the device.

The BPL and DLL will be built without the visibility of the {$ APPTYPE CONSOLE} directive, so I cannot use IFDEF conditional compilation. The BPL and DLL should be able to go anyway, depending on whether the main application is a regular winapp or console application.

One ugly solution that occurred to me was to use the name of the executable. ex:

 if (UpperCase(ExtractFileName(ParamStr(0))) = 'MYCONSOLEAPP.EXE') then ... 

But I do not want to do this, as I may have other console applications ...

Most likely, I have the magic function AmIAConsoleApp: boolean; Is there anything similar? I am using Delphi2005 in this project.

Update: I see that Iโ€™m kind of a duplicate of this question , but I would like to interview Delphi people to see if there is a better approach,

+6
source share
2 answers

Call GetStdHandle(Std_Output_Handle) . If it succeeds and returns zero, then the console does not need to be written. Other return values โ€‹โ€‹indicate that the console is connected to the process, so you can write to it (although the console may not be the most desirable place to register messages in the console program, since they will interfere with normal output). Something like that:

 function IAmAConsoleApp: Boolean; var Stdout: THandle; begin Stdout := GetStdHandle(Std_Output_Handle); Win32Check(Stdout <> Invalid_Handle_Value); Result := Stdout <> 0; end; 
+12
source

Use constructor injection to enter the registrar during instance creation. Here is a simple example.

Your proposed solution to check if the application is a console application works only for these two scenarios. The constructor injection solution contains almost no code and works wherever an exit is required.

+1
source

Source: https://habr.com/ru/post/895803/


All Articles