很多時(shí)候,調(diào)試GUI程序是很不方便的,通常的做法是使用MessageBox,但是作為一個(gè)模態(tài)窗口,它經(jīng)常產(chǎn)生不必要的消息,比如killfocus, setfocus或者paint,從而影響調(diào)試的執(zhí)行過程。當(dāng)然,使用vc的調(diào)試器也不錯(cuò),但是這樣也很容易造成窗口切換從而產(chǎn)生干擾消息。
因此,如果能像在控制臺(tái)程序里那樣使用cin/cout對(duì)象或printf族函數(shù),會(huì)使得調(diào)試過程方便得多。而通常,windows是不會(huì)為GUI程序產(chǎn)生單獨(dú)的命令行窗口的。所以我們是看不到使用標(biāo)準(zhǔn)輸入輸出流輸出的東西的。既然系統(tǒng)不提供,那就自己動(dòng)手“造”出一個(gè)來吧!
下面是一個(gè)簡(jiǎn)單的控制臺(tái)窗口對(duì)象,它可以為你的程序創(chuàng)建一個(gè)命令行窗口,并將stdout,stdin和stderr重定向到這個(gè)命令行窗口。在程序中建立一個(gè)這樣的對(duì)象之后,就可以直接使用cin/cout/*printf來操縱這個(gè)新的命令行窗口了!
.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;
// 重定向標(biāo)準(zhǔn)輸入流句柄到新的控制臺(tái)窗口
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;
// 重定向標(biāo)準(zhǔn)輸出流句柄到新的控制臺(tái)窗口
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;
// 重定向標(biāo)準(zhǔn)錯(cuò)誤流句柄到新的控制臺(tái)窗口
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里建立這個(gè)對(duì)象,若在main里建立這個(gè)對(duì)象,則同樣會(huì)出現(xiàn)一個(gè)新的控制臺(tái)窗口。
#ifdef _DEBUG // 當(dāng)然,在release版里同樣可以使用
Console notused;
#endif