I’ve recently encountered the following problem with my application: it didn’t show any console output, though the console had been allocated by using AllocConsole. I managed to figure out soon that it was caused by an attempt (hidden deeply in code) to write to the console before the AllocConsole was called. So it looked like this:
Console.WriteLine("Foo"); // no console allocated yet
AllocConsole(); // console window appears
Console.WriteLine("Bar"); // expecting "Bar" in the console, but the console is blank
So my question is: why does this happen? I don’t see any exceptions (though I suppose they are there).
The first time you use
Console.WriteLine, theConsoleclass creates aTextWriterand associates it with theConsole.Outproperty. The way it does this is to use Win32 to open the low-level file handle associated with the standard output file handle. If the standard output handle is invalid,Console.Outis set toTextWriter.Null, which discards all output.The Win32
AllocConsolefunction, creates and sets the standard output handle so after calling it the standard output handle is either different or now valid. In either case,Console.Outhas already been set either to use the old standard output or to discard all output.To force a re-open of
Console.Outafter callingAllocConsole, you can use this method:Console.OpenStandardOutput