GUI程序也能使用控制台窗口

很多时候,调试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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值