mfc程序下调用console窗口

这是从网上看到的一个调用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输出都会出现在这个窗口中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值