The problem:
I recently created a C# project where I wanted both a GUI and a command line interface. I started out with a Windows Forms application, but when it came time to add a command line interface, I realized that Console.WriteLine() didn't work because in the project properties it is explicitly set as a Windows Application.
The solution:
The AllocConsole() function allocates a new console so that Console.WriteLine() output will actually show up.
At the top of your main Program.cs file include this:
using System.Runtime.InteropServices;
Add this somewhere in that file:
[DllImport("kernel32.dll")]
private static extern bool AllocConsole();
Then rework the main method in that file to look something like this:
[STAThread]
static void Main(string[] args)
{
if (args.Length == 0)
{
// Render GUI
}
else
{
AllocConsole();
// Do command line stuff
Console.WriteLine("Finished. Press any key to continue.");
Console.ReadLine();
}
}
A possible issue is that when the new console is allocated, it disappears after execution is complete. If you want the console window to stay up (long enough for the user to read it, say), you could stick in a Console.ReadLine() like shown above, and inform the user that they need to press any key to continue. This will make the console wait for user input before it disappears.
If I set the output type to Console Application, then sure, that command would work. But then the GUI would have a console window visibly running in the background. Not acceptable, thank you very much.
The solution:
The AllocConsole() function allocates a new console so that Console.WriteLine() output will actually show up.
At the top of your main Program.cs file include this:
using System.Runtime.InteropServices;
Add this somewhere in that file:
[DllImport("kernel32.dll")]
private static extern bool AllocConsole();
Then rework the main method in that file to look something like this:
[STAThread]
static void Main(string[] args)
{
if (args.Length == 0)
{
// Render GUI
}
else
{
AllocConsole();
// Do command line stuff
Console.WriteLine("Finished. Press any key to continue.");
Console.ReadLine();
}
}
