分配控制台前调用Console.WriteLine [英] Calling Console.WriteLine before allocating the console
问题描述
我最近遇到了我的应用程序下面的问题:它没有表现出任何控制台输出,虽然控制台已被使用分配 AllocConsole
。我设法弄清楚很快,它是由一个尝试(在代码中隐藏较深)而造成写入 AllocConsole
调用之前控制台。因此,它是这样的:
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).
推荐答案
在第一次使用 Console.WriteLine
的控制台
类创建一个的TextWriter
,并将它与同伙 Console.Out
属性。它这样做的方式是使用Win32的打开与标准输出文件句柄相关联的低级别的文件句柄。如果标准输出句柄无效, Console.Out
设置为 TextWriter.Null
,该丢弃所有的输出。
The first time you use Console.WriteLine
, the Console
class creates a TextWriter
and associates it with the Console.Out
property. 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.Out
is set to TextWriter.Null
, which discards all output.
在Win32 AllocConsole
功能,创建和设置标准输出句柄因此调用后的标准输出句柄可以是不同的,现在还是有效的。在这两种情况下, Console.Out
已设定既可以使用的老的标准输出或放弃所有的输出。
The Win32 AllocConsole
function, 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.Out
has already been set either to use the old standard output or to discard all output.
要强制重新开放后,调用 Console.Out
的 AllocConsole
,你可以用这个方法:
To force a re-open of Console.Out
after calling AllocConsole
, you can use this method:
这篇关于分配控制台前调用Console.WriteLine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!