代码改变世界

开发GUI程序时同时打开一个控制台窗口进行调试多么惬意啊

2010-08-12 21:19  MudooT  阅读(1354)  评论(0编辑  收藏  举报

 

 

 

  你是否在一个函数中嵌套了MessageBox用来输出某些值?如果你这么做过,那么你肯定知道这有多痛苦了!那么你肯定想要开另外的一个控制台窗口来解决这个问题,那么现在就教给你这个办法。

  在WinAPI中有这样的一个函数AllocConsole(),这个函数顾名思义,alloc一个console。什么?就这么简单?对啊,就这么简单。在CreateWindow之前调用这个函数就可以了!哦,你说调用后不管是cout还是printf都不好使?哦,那当然了,你还需要把stdio重定向过来呀!也很简单!

freopen("conin$", "r+t", stdin);
freopen(
"conout$", "w+t", stdout);
freopen(
"conout$", "w+t", stderr);

   哦对了,别忘了在结束程序前关掉这些“文件”哟!

 

fclose(stderr);
fclose(stdout);
fclose(stdin);

 

最关键的,既然有alloc就一定得有free了!不错,调用FreeConsole()来结束这一切吧!

请记住,控制台只能开一个!所以最好用一个singleton来封装它!

 

代码
#include <stdio.h>
#include
<windows.h>

class CDebugConsole
{
public:
static CDebugConsole* getInstance()
{
static CDebugConsole* _o = new CDebugConsole;
return _o;
}
~CDebugConsole(void)
{
fclose(stderr);
fclose(stdout);
fclose(stdin);
FreeConsole();
}
private:
CDebugConsole(
void)
{
AllocConsole();
SetConsoleTitle(
"Debug Console");
freopen(
"conin$", "r+t", stdin);
freopen(
"conout$", "w+t", stdout);
freopen(
"conout$", "w+t", stderr);
}
CDebugConsole(
const CDebugConsole&);
CDebugConsole
& operator=(const CDebugConsole&);
};

 

恩 这样的话,你就不会多次调用拉!

使用的时候只需要CDebugConsole::getInstance()就可以了!

是不是把你多年悲剧的MessageBox忘掉了?