Ok, I've always used the AllocConsole()
method for console output when it comes to needing a Winform as well, because I use a wide variety of color when it comes to writing to console.
Using VS 2015 and below, AllocConsole in Debug mode always worked properly, Console.WriteLine
wrote to it properly. Now using VS 2017, The Console Shows when AllocConsole is called, however, instead of console.WriteLine outputs going to that console, it is going to the Output window of Visual Studio.
I prefer to use the AllocConsole rather than the Output window because I rely heavily on color. I've done plenty of searching on how to fix this, but I can't seem to find an answer.
AllocConsole()
does not work on it's own, because VS 2017 does some "debug stdout redirect magic". To fix this you need to create a console with AllocConsole()
and fix the stdout handle.
Here is the snipped I found:
[DllImport("kernel32.dll",
EntryPoint = "AllocConsole",
SetLastError = true,
CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
private static extern int AllocConsole();
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
uint lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
uint hTemplateFile);
private const int MY_CODE_PAGE = 437;
private const uint GENERIC_WRITE = 0x40000000;
private const uint FILE_SHARE_WRITE = 0x2;
private const uint OPEN_EXISTING = 0x3;
public static void CreateConsole()
{
AllocConsole();
IntPtr stdHandle = CreateFile(
"CONOUT$",
GENERIC_WRITE,
FILE_SHARE_WRITE,
0, OPEN_EXISTING, 0, 0
);
SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, true);
FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);
Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE);
StreamWriter standardOutput = new StreamWriter(fileStream, encoding);
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
Console.Write("This will show up in the Console window.");
}
Special thanks to Ramkumar Ramesh for the work-around: Console Output is gone in VS2017