Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching Console to C# Windows Application with STDOUT Print Statements

Tags:

c#

windows

stdout

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?

like image 306
Ben W Avatar asked Jan 24 '26 23:01

Ben W


1 Answers

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

like image 150
PhonicUK Avatar answered Jan 26 '26 14:01

PhonicUK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!