一个简单的将GUI程序的log信息输出到关联的Console窗口中(AllocConsole SetConsoleTitle WriteConsole 最后用ShowWindow(GetConsoleWindow)进行显示)

[cpp] view plain copy
 
  1. // .h 文件  
  2. #pragma once  
  3. class CConsoleDump  
  4. {  
  5. public:  
  6.     explicit CConsoleDump(LPCTSTR lpszWindowTitle = NULL);  
  7.     virtual ~CConsoleDump(void);  
  8.   
  9. public:  
  10.     BOOL DUMP(LPCTSTR lpszFmt, ...);  
  11.     BOOL ShowWindow(BOOL bShowWindow);  
  12.     BOOL SetWindowText(LPCTSTR lpszWindowTitle = NULL);  
  13. };  
  14.   
  15. // .cpp文件  
  16. #include "StdAfx.h"  
  17. #include "ConsoleDump.h"  
  18.   
  19. #define MAX_BUFFER_SIZE (10 * 1024)  
  20.   
  21. CConsoleDump::CConsoleDump(LPCTSTR lpszWindowTitle)  
  22. {  
  23.     if(AllocConsole())  
  24.     {  
  25.         if(NULL != lpszWindowTitle)  
  26.         {  
  27.             SetConsoleTitle(lpszWindowTitle);  
  28.         }  
  29.     }  
  30. }  
  31.   
  32. CConsoleDump::~CConsoleDump(void)  
  33. {  
  34.     FreeConsole();  
  35. }  
  36.   
  37. BOOL CConsoleDump::ShowWindow(BOOL bShowWindow)  
  38. {  
  39.     return ::ShowWindow(GetConsoleWindow(), bShowWindow ? SW_SHOW : SW_HIDE);  
  40. }  
  41.   
  42. BOOL SetWindowText(LPCTSTR lpszWindowTitle)  
  43. {  
  44.     if(NULL != lpszWindowTitle)  
  45.     {  
  46.         return SetConsoleTitle(lpszWindowTitle);  
  47.     }  
  48.     return TRUE;  
  49. }  
  50.   
  51. BOOL CConsoleDump::DUMP(LPCTSTR lpszFmt, ...)  
  52. {  
  53.     TCHAR szText[MAX_BUFFER_SIZE] = {0};  
  54.   
  55.     va_list arglist;  
  56.     va_start(arglist, lpszFmt);  
  57.     _vstprintf_s(szText, _countof(szText), lpszFmt, arglist);  
  58.     va_end(arglist);  
  59.   
  60.     return WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), szText, _tcslen(szText), NULL, NULL);  
  61. }  
  62.   
  63. // 测试使用  
  64. CConsoleDump m_dump; // 定义为类的成员变量  
  65. // 需要的地方利用CConsoleDump::DUMP函数输出log信息即可  
  66. m_dump.DUMP(_T("Hello, World! "));  


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

http://blog.csdn.net/visualeleven/article/details/7628564

原文地址:https://www.cnblogs.com/findumars/p/6001859.html