很多時候,調試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