Ben W
Ben W

Reputation: 1050

Attaching Console to C# Windows Application with STDOUT Print Statements

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?

Upvotes: 4

Views: 2099

Answers (1)

PhonicUK
PhonicUK

Reputation: 13864

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

Upvotes: 1

Related Questions