一个简单的将GUI程序的log信息输出到关联的Console窗口中

// .h 文件
#pragma once
class CConsoleDump
{
public:
	explicit CConsoleDump(LPCTSTR lpszWindowTitle = NULL);
	virtual ~CConsoleDump(void);

public:
	BOOL DUMP(LPCTSTR lpszFmt, ...);
	BOOL ShowWindow(BOOL bShowWindow);
	BOOL SetWindowText(LPCTSTR lpszWindowTitle = NULL);
};

// .cpp文件
#include "StdAfx.h"
#include "ConsoleDump.h"

#define MAX_BUFFER_SIZE (10 * 1024)

CConsoleDump::CConsoleDump(LPCTSTR lpszWindowTitle)
{
	if(AllocConsole())
	{
		if(NULL != lpszWindowTitle)
		{
			SetConsoleTitle(lpszWindowTitle);
		}
	}
}

CConsoleDump::~CConsoleDump(void)
{
	FreeConsole();
}

BOOL CConsoleDump::ShowWindow(BOOL bShowWindow)
{
	return ::ShowWindow(GetConsoleWindow(), bShowWindow ? SW_SHOW : SW_HIDE);
}

BOOL SetWindowText(LPCTSTR lpszWindowTitle)
{
	if(NULL != lpszWindowTitle)
	{
		return SetConsoleTitle(lpszWindowTitle);
	}
	return TRUE;
}

BOOL CConsoleDump::DUMP(LPCTSTR lpszFmt, ...)
{
	TCHAR szText[MAX_BUFFER_SIZE] = {0};

	va_list arglist;
	va_start(arglist, lpszFmt);
	_vstprintf_s(szText, _countof(szText), lpszFmt, arglist);
	va_end(arglist);

	return WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), szText, _tcslen(szText), NULL, NULL);
}

// 测试使用
CConsoleDump m_dump; // 定义为类的成员变量
// 需要的地方利用CConsoleDump::DUMP函数输出log信息即可
m_dump.DUMP(_T("Hello, World!\r\n"));

这只是个简单的封装了Console相关的几个函数,关于更多的Console相关的控制,可以参考MSDN文档中的

猜你喜欢

转载自blog.csdn.net/visualeleven/article/details/7628564