65.9K
CodeProject 正在变化。 阅读更多。
Home

为 MFC 应用程序的调试输出创建控制台

2000年6月18日

viewsIcon

223699

downloadIcon

2673

如何将调试输出发送到 MFC 应用程序中的控制台。

Sample Image - MFCConsole.gif

引言

在你的 MFC 应用程序中将消息打印到控制台,只需要三个函数调用。你可能希望将调试输出发送到控制台的原因有很多。我的原因是,首先,我测试应用程序的调试版本时,PC 上没有 IDE;其次,主框架并不总是可见的,这使情况变得更糟。

在此先提醒一句:关闭控制台窗口将退出你的应用程序!我们开始吧

创建控制台

要创建控制台窗口,你需要调用 AllocConsole()。此函数不接受任何参数,并返回一个 BOOL,指示是否已创建控制台。你应该在代码的开头某个时候创建控制台。在示例中,我将代码放在了 CWinApp::OnInitInstance() 重载中。就像这样

BOOL CSmplConsoleApp::InitInstance()
{
	// details omitted

	// allocate a console
#ifdef _DEBUG
	if (!AllocConsole())
		AfxMessageBox("Failed to create the console!", MB_ICONEXCLAMATION);
#endif
	return TRUE;
	
	//	and then create the frame
	pFrame->LoadFrame(IDR_MAINFRAME,
		WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, NULL,
		NULL);

	// The one and only window has been initialized, so show and update it.
	pFrame->ShowWindow(SW_SHOW);
	pFrame->UpdateWindow();
}

重要的是,你必须在创建主窗口之前创建你的控制台。否则,控制台仍然会被创建,但使用 _cprintf() 发送的调试消息将不会到达你的控制台。我搞不清楚为什么会这样,只是知道就是这样。如果有人有解释,请告诉我。

写入控制台

通过 _cprintf() 将你的输出发送到控制台,其原型如下

int _cprintf( const char *format [, argument] ... );

格式与 printf() 函数的格式参数的形式和功能相同。请在你的文档中查找详细信息。并且不要忘记在任何使用 _cprintf() 的地方包含 #include <conio.h>

演示应用程序中的 CChildView::OnPaint() 重载如下所示

void CChildView::OnPaint() 
{
	CPaintDC dc(this); // device context for painting
	
	// TODO: Add your message handler code here
#ifdef _DEBUG
	static int nCallCounter = 0;
	nCallCounter++;
	_cprintf("Window painted now %i time(s)\n", nCallCounter);
#endif
	// Do not call CWnd::OnPaint() for painting messages
}

移除控制台

在程序的结尾附近,你应该调用 FreeConsole() 来释放控制台 <g>。同样,此函数不接受任何参数,并返回一个 BOOL,指示成功或失败。以下是演示项目中 CWinApp::ExitInstance() 重载的样子

int CSmplConsoleApp::ExitInstance() 
{
	//	deallocate console
#ifdef _DEBUG
	if (!FreeConsole())
		AfxMessageBox("Could not free the console!");
#endif
	return CWinApp::ExitInstance();
}

希望这有帮助!

许可证

本文未附加明确的许可证,但可能在文章文本或下载文件本身中包含使用条款。如有疑问,请通过下面的讨论区联系作者。

作者可能使用的许可证列表可以在此处找到。

© . All rights reserved.