Leaves One

Alan Richard's Blog

Console.Write Not Showing Output in C# Windows Application - Solution

Situation

I am developing a program that combines GUI and console output.

The program converts the input image into a monochromatic BMP.

If the argument is empty, the program will pop up a file dialog to let the user select an image.

Off-topic Note: monochromatic ≠ single channel (or grayscale). Monochromatic means that the image is either black or white and has only one bit per pixel.

For simplicity, I created a WinForm project and added some logic to the Program.cs which includes some Console.WriteLine() statements.

Problem

However, when I run the program in terminal, the console output is not shown.

Not showing output

Attempt

I tried the following solution:

Program.cs

using System.Runtime.InteropServices;

internal static class Program
{
[STAThread]
static void Main(string[] args)
{
AllocConsole();
// ...
}
}

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();

This actually works, but there’s a problem: what it actually does is to create a new console window. What I want is to print the output to the terminal window where I ran the program.

New console window

Solution

Finally I found a working solution which is way too simple:
Go to the project properties, and change the output type to Console Application.


Or, you can edit the .csproj file and change the OutputType to Exe.

<OutputType>Exe</OutputType> 

It will not break the GUI, and the console output will be shown in the terminal window now.

Output and GUI working

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
If you checked “Remember me”, your email address and name will be stored in your browser for your convenience.