MFC工程加入控制台调试信息输出

来源:互联网 发布:尼古丁 知乎 编辑:程序博客网 时间:2024/05/18 05:00

MFC工程加入控制台调试信息输出

  在MFC程序中,可以使用TRACE宏或者OutPutDebugString()函数输出调试信息,TRACE宏可以在调试时像Output窗口输出调试信息,OutPutDebugString()函数的输出则可以用DebugView捕获(DebugView也可以捕获TRACE宏的输出,其官网在 这里 ,具体使用请参考官网的说明),另外也可以通过AfxMessageBox()或者MessageBox()弹窗输出,但毕竟太多繁琐,每弹出一个窗口便要确认一次。引入日志库也是个好办法,同时也可以通过分析日志文件了解应用程序的运行状况,这是终极大杀器,我们还需要更轻量级的方法。

  控制台调试信息输出,即是在程序运行时,打开一个Console窗口,将自己编写的调试信息输出到Console中,便于了解当前程序的运行状况,帮助调试,仅需简单几行代码即可搞定,不需要动用日志库这样重量级的东东。

  本文以一个基于对话框的MFC程序为例,看看如何给应用程序加上控制台输出。

  1、实例工程名为Demo,在CDemoDlg.cpp中加入头文件 #include "conio.h" 

  2、在CDemoDlg::OnInitDialog() {...}函数中加入AllocConsole();

  3、在需要输出调试信息的地方,调用 cprintf() (在VS2005后应该用 _cprintf 代替,下文有说明)函数输出信息,用法同 printf() 函数类似;

  4、若需要关闭控制台输出,调用 FreeConsole();

  在MSDN(MSDN Library Visual Studio 2008 SP1)中,AllocConsole()函数的原型为:

?
1
  BOOL WINAPI AllocConsole(void);

  Return Value:

  If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.

  Remarks:

  A process can be associated with only one console, so the AllocConsole function fails if the calling process already has a console. A process can use the FreeConsole function to detach itself from its current console, then it can call AllocConsole to create a new console or AttachConsole to attach to another console.

  If the calling process creates a child process, the child inherits the new console.

  AllocConsole initializes standard input, standard output, and standard error handles for the new console. The standard input handle is a handle to the console's input buffer, and the standard output and standard error handles are handles to the console's screen buffer. To retrieve these handles, use the GetStdHandle function.

  This function is primarily used by graphical user interface (GUI) application to create a console window. GUI applications are initialized without a console. Console applications are initialized with a console, unless they are created as detached processes (by calling the CreateProcess function with the DETACHED_PROCESS flag).

  MSDN中对于cprintf()的解释,很简短,只有一句话

  "This POSIX function is deprecated beginning in Visual C++ 2005. Use the ISO C++ conformant _cprintf or security-enhanced _cprintf_s instead."

  从VS2005开始,用 _cprintf 或 _cprintf_s 函数代替 cprintf ,So then,再来看下 _cprintf 的解释,更加简短了:Formats and prints to the console.

按照我的理解,就是 _cprintf 是像控制台输出格式化信息,c 即是console的意思,而 printf 是标准输出,不一定是控制台窗口了。

0 0
原创粉丝点击