在WinMain中嵌Console窗口



  • 博客分类: 
  • C++
 

很多时候,调试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 <io.h>
#include <fcntl.h>
#include <stdio.h>
#include <windows.h>

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<intptr_t>(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<intptr_t>(hStd), _O_TEXT); //文本模式
  file = _fdopen(fd, "w");
  setvbuf(file, NULL, _IONBF, 0); // 无缓冲
  *stdout = *file;

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

  hStd = GetStdHandle(STD_ERROR_HANDLE);
  fd = _open_osfhandle(reinterpret_cast<intptr_t>(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 <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <iostream>
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<<"Microsoft Windows Media Player"<<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 ");   
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值