在编写复杂程序的过程中,我们经常需要将一些信息输出到文件或者屏幕上。较控制台应用程序,MFC窗体程序要显得麻烦一些!
下面有2种方法来实现为MFC窗体程序添加调试控制台,方便程序员调试程序和了解当前程序的运行状态。
重要Windows API:AllocConsole(); //创建Console窗口
FreeConsole(); //销毁Console窗口
(1)启动控制台窗口
需要包含的头文件
#include <io.h>
#include <cstdio>
#include <FCNTL.H>
void CTestDebugConsoleDlg::OnBnClickedButton6()
{
// start debugconsole
AllocConsole();
intptr_t handle= (intptr_t)GetStdHandle(STD_OUTPUT_HANDLE);
int hCrt = _open_osfhandle(handle,_O_TEXT);
FILE * hf = _fdopen( hCrt, "w" );
*stdout =*hf;
char title[1024] ={0};
sprintf_s(title, 1024, "DebugCosole[%u]", (unsigned long)(this->GetSafeHwnd()));
SetConsoleTitle(title);
SetConsoleTextAttribute((HANDLE)handle, FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
HWND hwnd=NULL;
while(NULL==hwnd) hwnd=::FindWindow(NULL,(LPCTSTR)title);
HMENU hmenu = ::GetSystemMenu ( hwnd, FALSE );
DeleteMenu ( hmenu, SC_CLOSE, MF_BYCOMMAND );
}
{
// start debugconsole
AllocConsole();
intptr_t handle= (intptr_t)GetStdHandle(STD_OUTPUT_HANDLE);
int hCrt = _open_osfhandle(handle,_O_TEXT);
FILE * hf = _fdopen( hCrt, "w" );
*stdout =*hf;
char title[1024] ={0};
sprintf_s(title, 1024, "DebugCosole[%u]", (unsigned long)(this->GetSafeHwnd()));
SetConsoleTitle(title);
SetConsoleTextAttribute((HANDLE)handle, FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
HWND hwnd=NULL;
while(NULL==hwnd) hwnd=::FindWindow(NULL,(LPCTSTR)title);
HMENU hmenu = ::GetSystemMenu ( hwnd, FALSE );
DeleteMenu ( hmenu, SC_CLOSE, MF_BYCOMMAND );
}
MFC窗体测试程序:
Console信息显示:
代码下载(VS2008):https://files.cnblogs.com/kekec/DebugConsole.rar
(2)设计另外一个MFC窗体程序
关于这种方法请详见 Azure Product 的 “实现一个通用的调试控制台”。