4

I have a C# GUI application that also supports a command line mode for server-side scripting. My application keys off of the number of input arguments, and if > 0, attaches the parent console.

[DllImport("kernel32.dll")]
static extern bool AttachConsole(int dwProcessId);
private const int ATTACH_PARENT_PROCESS = -1;

[STAThread]
static void Main(string[] args)
{
    bool runningFromConsole = args.Length > 0 && AttachConsole(ATTACH_PARENT_PROCESS);
    if(runningFromConsole)
        // Handle input arguments
    else
        // Launch GUI
}

I am able to successfully write text to the console with Console.Out.WriteLine("Text");, but the line is not sent to the console as a STDOUT (or STDERR if I use Console.Error.WriteLine("Text")).

When running my application locally, this is not a big deal, but when running on a build server, the application returns do not register. Right now, I am working around the issue by creating a supplimental log file that I type application.log to the console once my application finishes running.

Is there a way for force text printed to the console to be sent as STDOUT/STDERR?

Ben W
  • 930
  • 6
  • 16
  • I/O redirection requires you to create a console mode app, it can't work for a gui app and AttachConsole is too late. Also note that the Console.Write output intermingles with the cmd.exe output and that Console.Read is not reliable since cmd.exe is reading as well. Cmd.exe doesn't know that it needs to block until app.exe finished running. Consider to create a basic console mode app that simply starts app.exe when there are no arguments. You can even rename it to app.com so it automatically runs when the user types "app /foo /bar" in the command line. – Hans Passant Aug 09 '18 at 13:28
  • Build it as Console application instead of Windows Application. – Code Name Jack Aug 09 '18 at 13:29

1 Answers1

1

AttachConsole doesn't quite behave the way you expect, what you need to do often is to AllocConsole and change your stdio handles to use that console.

The accepted answer for this question I can verify works in this scenario because I've used it: No console output when using AllocConsole and target architecture x86

PhonicUK
  • 13,486
  • 4
  • 43
  • 62
  • Thanks for the help! This answer in combination with [get-the-handle-and-write-to-the-console-that-launched-our-process](https://stackoverflow.com/questions/5711291/get-the-handle-and-write-to-the-console-that-launched-our-process) solved my problem – Ben W Aug 09 '18 at 14:49
  • I assume that "behave the way you expect" is referring to how an interactive CMD shell (not a batch script) only waits for console applications to exit. It won't wait for a GUI app. If a GUI child attaches to the shell's console, it might be ok (but messy) to write log messages to the console, but it would be confusing to try to read from the console input buffer at the same time as the shell. – Eryk Sun Aug 16 '18 at 15:21