---
title: "在WinMain中嵌Console窗口"
author: "kenkao"
date: "2012-07-23T12:13:02Z"
tags: []
categories: ["编程语言"]
slug: "winmain-console"
draft: false
lastmod: "2012-07-23T12:13:02Z"
id: 1604136
url: "https://kenkao.iteye.com/blog/1604136"
---

很多时候，调试GUI程序是很不方便的，通常的做法是使用MessageBox，但是作为一个模态窗口，它经常产生不必要的消息，比如killfocus, setfocus或者paint，从而影响调试的执行过程。当然，使用vc的调试器也不错，但是这样也很容易造成窗口切换从而产生干扰消息。  
因此，如果能像在控制台程序里那样使用cin/cout对象或printf族函数，会使得调试过程方便得多。而通常，windows是不会为GUI程序产生单独的命令行窗口的。所以我们是看不到使用标准输入输出流输出的东西的。既然系统不提供，那就自己动手“造”出一个来吧！

下面是一个简单的控制台窗口对象，它可以为你的程序创建一个命令行窗口，并将stdout,stdin和stderr重定向到这个命令行窗口。在程序中建立一个这样的对象之后，就可以直接使用cin/cout/\*printf来操纵这个新的命令行窗口了！

.h文件  
#ifndef \_CUSTOM\_CONSOLE_  
#define \_CUSTOM\_CONSOLE_

#include &lt;io.h&gt;  
#include &lt;fcntl.h&gt;  
#include &lt;stdio.h&gt;  
#include &lt;windows.h&gt;

class Console  
{  
public:  
 Console();  
 Console(LPCTSTR lpszTitle, SHORT ConsoleHeight = 300, SHORT ConsoleWidth = 80);  
 ~Console();

private:  
 void Attach(SHORT ConsoleHeight, SHORT ConsoleWidth);  
 static BOOL IsExistent;  
};

#endif

.cpp文件

#include "\*\*\*.h"

 BOOL Console::IsExistent = FALSE;

 Console::Console()  
 {  
  if (IsExistent)  
   return;

  AllocConsole();  
  Attach(300, 80);

  IsExistent = TRUE;  
 }

 Console::Console(LPCTSTR lpszTitle, SHORT ConsoleHeight, SHORT ConsoleWidth)  
 {  
  if (IsExistent)  
   return;

  AllocConsole();  
  SetConsoleTitle(lpszTitle);  
  Attach(ConsoleHeight, ConsoleWidth);

  IsExistent = TRUE;  
 }

 void Console::Attach(SHORT ConsoleHeight, SHORT ConsoleWidth)  
 {  
  HANDLE  hStd;  
  int     fd;  
  FILE    \*file;

// 重定向标准输入流句柄到新的控制台窗口

  hStd = GetStdHandle(STD\_INPUT\_HANDLE);  
  fd = \_open\_osfhandle(reinterpret\_cast&lt;intptr\_t&gt;(hStd), \_O\_TEXT); // 文本模式  
  file = \_fdopen(fd, "r");  
  setvbuf(file, NULL, \_IONBF, 0); // 无缓冲  
  \*stdin = \*file;

// 重定向标准输出流句柄到新的控制台窗口

  hStd = GetStdHandle(STD\_OUTPUT\_HANDLE);  
  COORD size;  
  size.X = ConsoleWidth;  
  size.Y = ConsoleHeight;  
  SetConsoleScreenBufferSize(hStd, size);  
  fd = \_open\_osfhandle(reinterpret\_cast&lt;intptr\_t&gt;(hStd), \_O\_TEXT); //文本模式  
  file = \_fdopen(fd, "w");  
  setvbuf(file, NULL, \_IONBF, 0); // 无缓冲  
  \*stdout = \*file;

// 重定向标准错误流句柄到新的控制台窗口

  hStd = GetStdHandle(STD\_ERROR\_HANDLE);  
  fd = \_open\_osfhandle(reinterpret\_cast&lt;intptr\_t&gt;(hStd), \_O\_TEXT); // 文本模式  
  file = \_fdopen(fd, "w");  
  setvbuf(file, NULL, \_IONBF, 0); // 无缓冲  
  \*stderr = \*file;

 }

 Console::~Console()  
 {  
  if (IsExistent)  
  {  
   FreeConsole();  
   IsExistent = FALSE;  
  }  
 }

可以在WinMain里建立这个对象，若在main里建立这个对象，则同样会出现一个新的控制台窗口。  
#ifdef \_DEBUG // 当然，在release版里同样可以使用  
Console notused;  
#endif

 

 

// UnInCmd.cpp : 定义应用程序的入口点。  
//

#include "stdafx.h"  
#include "UnInCmd.h"

#include &lt;stdio.h&gt;  
#include &lt;fcntl.h&gt;  
#include &lt;io.h&gt;  
#include &lt;iostream&gt;  
using namespace std;

#define MAX\_LOADSTRING 100

// 全局变量：  
HINSTANCE hInst;        // 当前实例  
TCHAR  szTitle\[MAX\_LOADSTRING];     // 标题栏文本  
TCHAR  szWindowClass\[MAX\_LOADSTRING];   // 主窗口类名  
HANDLE      hIn  = NULL;  
HANDLE  hOut = NULL;  
HANDLE      hErr = NULL;

// 此代码模块中包含的函数的前向声明：  
ATOM    MyRegisterClass(HINSTANCE hInstance);  
BOOL    InitInstance(HINSTANCE, int);  
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);  
LRESULT CALLBACK About(HWND, UINT, WPARAM, LPARAM);

void OutputString(LPCTSTR szString);

int APIENTRY \_tWinMain(HINSTANCE hInstance,  
                     HINSTANCE hPrevInstance,  
                     LPTSTR    lpCmdLine,  
                     int       nCmdShow)  
{  
  // TODO: 在此放置代码。  
 MSG msg;  
 HACCEL hAccelTable;

 // 初始化全局字符串  
 LoadString(hInstance, IDS\_APP\_TITLE, szTitle, MAX\_LOADSTRING);  
 LoadString(hInstance, IDC\_UNINCMD, szWindowClass, MAX\_LOADSTRING);  
 MyRegisterClass(hInstance);

 // 执行应用程序初始化：  
 if (!InitInstance (hInstance, nCmdShow))  
 {  
  return FALSE;  
 }  
     
 AllocConsole();  
 DWORD dwbytesWritten;  
 char \*msg1 = "第一条消息\\n";

    hIn = GetStdHandle(STD\_INPUT\_HANDLE);  
 hOut = GetStdHandle(STD\_OUTPUT\_HANDLE);  
 hErr = GetStdHandle(STD\_ERROR\_HANDLE);

    SetConsoleTitle("内嵌Cmd");  
    FILE \*hf = NULL;  
 char buf\[2];

    int hCrt = 0;

    //输出  
 hCrt = \_open\_osfhandle((long)hOut,\_O\_TEXT);  
 hf = \_fdopen(hCrt,"w");    //表示可写  
 setvbuf(hf,buf,\_IONBF,1);  
 \*stdout = \*hf;  
     
 //输入  
 int hCirt = 0;  
 hCirt = \_open\_osfhandle((long)hIn,\_O\_TEXT);  
 FILE    \*hfIn = NULL;  
 hfIn = \_fdopen(hCirt,"r");  
    setvbuf(hfIn,buf,\_IONBF,1);  
 \*stdin = \*hfIn;  
     
 //错误  
 int hErt = 0;  
 hErt = \_open\_osfhandle((long)hErr,\_O\_TEXT);  
 FILE   \*hfErr = NULL;  
    hfErr = \_fdopen(hErt,"w");  
    setvbuf(hfErr,buf,\_IONBF,1);  
 \*stderr = \*hfErr;

 cout&lt;&lt;"Microsoft Windows Media Player"&lt;&lt;endl;

 hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC\_UNINCMD);

 // 主消息循环：  
 while (GetMessage(&msg, NULL, 0, 0))  
 {  
  if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))  
  {  
   TranslateMessage(&msg);  
   DispatchMessage(&msg);  
  }  
 }  
     
 FreeConsole();  
 return (int) msg.wParam;  
}

 

//  
//  函数：MyRegisterClass()  
//  
//  目的：注册窗口类。  
//  
//  注释：  
//  
//    仅当希望在已添加到 Windows 95 的  
//    “RegisterClassEx”函数之前此代码与 Win32 系统兼容时，  
//    才需要此函数及其用法。调用此函数  
//    十分重要，这样应用程序就可以获得关联的  
//   “格式正确的”小图标。  
//  
ATOM MyRegisterClass(HINSTANCE hInstance)  
{  
 WNDCLASSEX wcex;

 wcex.cbSize = sizeof(WNDCLASSEX);

 wcex.style   = CS\_HREDRAW | CS\_VREDRAW;  
 wcex.lpfnWndProc = (WNDPROC)WndProc;  
 wcex.cbClsExtra  = 0;  
 wcex.cbWndExtra  = 0;  
 wcex.hInstance  = hInstance;  
 wcex.hIcon   = LoadIcon(hInstance, (LPCTSTR)IDI\_UNINCMD);  
 wcex.hCursor  = LoadCursor(NULL, IDC\_ARROW);  
 wcex.hbrBackground = (HBRUSH)(COLOR\_WINDOW+1);  
 wcex.lpszMenuName = (LPCTSTR)IDC\_UNINCMD;  
 wcex.lpszClassName = szWindowClass;  
 wcex.hIconSm  = LoadIcon(wcex.hInstance, (LPCTSTR)IDI\_SMALL);

 return RegisterClassEx(&wcex);  
}

//  
//   函数：InitInstance(HANDLE, int)  
//  
//   目的：保存实例句柄并创建主窗口  
//  
//   注释：  
//  
//        在此函数中，我们在全局变量中保存实例句柄并  
//        创建和显示主程序窗口。  
//  
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)  
{  
   HWND hWnd;

   hInst = hInstance; // 将实例句柄存储在全局变量中

   hWnd = CreateWindow(szWindowClass, szTitle, WS\_OVERLAPPEDWINDOW,  
      CW\_USEDEFAULT, 0, CW\_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   if (!hWnd)  
   {  
      return FALSE;  
   }

   ShowWindow(hWnd, nCmdShow);  
   UpdateWindow(hWnd);

   return TRUE;  
}

//  
//  函数：WndProc(HWND, unsigned, WORD, LONG)  
//  
//  目的：处理主窗口的消息。  
//  
//  WM\_COMMAND - 处理应用程序菜单  
//  WM\_PAINT - 绘制主窗口  
//  WM\_DESTROY - 发送退出消息并返回  
//  
//  
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)  
{  
 int wmId, wmEvent;  
 PAINTSTRUCT ps;  
 HDC hdc;

 switch (message)  
 {  
 case WM\_COMMAND:  
  wmId    = LOWORD(wParam);  
  wmEvent = HIWORD(wParam);  
  // 分析菜单选择：  
  switch (wmId)  
  {  
  case IDM\_ABOUT:  
   DialogBox(hInst, (LPCTSTR)IDD\_ABOUTBOX, hWnd, (DLGPROC)About);  
   break;  
  case IDM\_EXIT:  
   DestroyWindow(hWnd);  
   break;  
  default:  
   return DefWindowProc(hWnd, message, wParam, lParam);  
  }  
  break;  
 case WM\_PAINT:  
  hdc = BeginPaint(hWnd, &ps);  
  // TODO: 在此添加任意绘图代码...  
  EndPaint(hWnd, &ps);  
  break;  
 case WM\_DESTROY:  
  PostQuitMessage(0);  
  break;  
 default:  
  return DefWindowProc(hWnd, message, wParam, lParam);  
 }  
 return 0;  
}

// “关于”框的消息处理程序。  
LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)  
{  
 switch (message)  
 {  
 case WM\_INITDIALOG:  
  return TRUE;

 case WM\_COMMAND:  
  if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)  
  {  
   EndDialog(hDlg, LOWORD(wParam));  
   return TRUE;  
  }  
  break;  
 }  
 return FALSE;  
}

void OutputString(LPCTSTR szString)  
{  
   DWORD dwBytesWritten;  
   WriteConsole(hOut,szString,(DWORD)strlen(szString),&dwBytesWritten,NULL);  
}

 

// 添加控制台窗口控制器的写法

 

BOOL   CtrlHandler(DWORD   fdwCtrlType)    
{    
        switch   (fdwCtrlType)    
        {    
                //   Handle   the   CTRL+C   signal.    
   
                case   CTRL\_C\_EVENT:    
   
                        Beep(1000,   1000);    
                        return   TRUE;    
   
                //   CTRL+CLOSE:   confirm   that   the   user   wants   to   exit.    
   
                case   CTRL\_CLOSE\_EVENT:    
   
                        return   TRUE;    
   
                //   Pass   other   signals   to   the   next   handler.    
   
                case   CTRL\_BREAK\_EVENT:    
   
                case   CTRL\_LOGOFF\_EVENT:    
   
                case   CTRL\_SHUTDOWN\_EVENT:    
   
                default:    
   
                        return   FALSE;    
        }    
}    
   
void   main(void)    
{    
        BOOL   fSuccess;    
   
        fSuccess   =   SetConsoleCtrlHandler(    
                (PHANDLER\_ROUTINE)   CtrlHandler,     //   handler   function    
                TRUE);                                                       //   add   to   list    
        if   (!   fSuccess)    
                MyErrorExit( "Could   not   set   control   handler ");    
}