在某些時候,我們可能需要在Win32窗口應(yīng)用程序中打開控制臺窗口,打印一些消息,或者作為當(dāng)前程序的另外一個人機交互界面,或者為了幫助調(diào)試程序。為了達到這種效果,需要了解函數(shù)AllocConsole和C-Runtime的freopen函數(shù)。
AllocConsole函數(shù)會為當(dāng)前的窗口程序申請一個Console窗口。這是MSDN上對AllocConsole的介紹:
AllocConsole
The AllocConsole function allocates a new console for the calling process.
BOOL AllocConsole(void);
函數(shù)調(diào)用成功,返回非零值,調(diào)用不成功則返回0.
在為當(dāng)前窗口程序申請到console后,我們需要調(diào)用C-Runtime的freopen函數(shù)將標(biāo)準輸出(stdout)重定位到新申請的console。
freopen的原型如下:
FILE *freopen(
const char *path,
const char *mode,
FILE *stream
);
我們調(diào)用的時候是這么著傳入?yún)?shù)的:
freopen("CONOUT$","w",stdout);
其中"CONOUT$"是指代當(dāng)前console的特殊字符串,"w"表明以written模式打開這個console,stdout指代的是系統(tǒng)的標(biāo)準輸出設(shè)備。
下面是整個的代碼:
if(AllocConsole())

{
freopen("CONOUT$","w",stdout);
printf("hello, world!");
}