这是从网上看到的一个调用console窗口的包装类,贴到这儿备用,呵呵。
ConsolePrinter.h
===================================================
// ConsolePrinter.h: interface for the CConsolePrinter class.
//
//
#if !defined(AFX_CONSOLEPRINTER_H__BC163867_C7BA_4756_BE7C_0D29C08105FD__INCLUDED_)
#define AFX_CONSOLEPRINTER_H__BC163867_C7BA_4756_BE7C_0D29C08105FD__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <io.h>
#include <iostream>
#include <fcntl.h>
class CConsolePrinter
{
public:
void print(const char* str);
static void Destroy();
static CConsolePrinter* Instance();
virtual ~CConsolePrinter();
protected:
CConsolePrinter();
private:
static CConsolePrinter* _instance;
FILE *file;
};
#endif // !defined(AFX_CONSOLEPRINTER_H__BC163867_C7BA_4756_BE7C_0D29C08105FD__INCLUDED_)
=====================================================
ConsolePrinter.cpp
===================================================
// ConsolePrinter.cpp: implementation of the CConsolePrinter class.
//
//
#include "stdafx.h"
#include "NIDS_MFC.h"
#include "ConsolePrinter.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//
// Construction/Destruction
//
CConsolePrinter* CConsolePrinter::_instance = 0;
CConsolePrinter::CConsolePrinter()
{
// create a new console to the process
AllocConsole();
int hCrun;
hCrun = _open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);
file = _fdopen(hCrun, "w");
// use default stream buffer
setvbuf(file, NULL, _IONBF, 0);
*stdout = *file;
std::cout << "Console is Ready!/n";
}
CConsolePrinter::~CConsolePrinter()
{
FreeConsole();
fclose(file);
}
CConsolePrinter* CConsolePrinter::Instance()
{
if (_instance == 0)
{
_instance = new CConsolePrinter;
}
return _instance;
}
void CConsolePrinter::Destroy()
{
if (_instance)
{
delete _instance;
}
_instance = 0;
}
void CConsolePrinter::print(const char *str)
{
std::cout << str << std::endl;
}
=======================================================
在窗体的初始化方法中调用这样的语句即可
=======================================================
/*显示console窗口*/
#ifdef _DEBUG
CConsolePrinter::Instance();
#endif
=======================================================
在窗体的销毁函数中添加
=========================================================
/*销毁console窗口*/
#ifdef _DEBUG
CConsolePrinter::Destroy();
#endif
==========================================================
运行程序,则可看见console窗口与主程序一起出现,程序中的console输出都会出现在这个窗口中。