// Console.h: interface for the CConsole class.調試
#endif // !defined(AFX_CONSOLE_H__833C45AE_1080_4666_B614_8C925BCB7FD2__INCLUDED_)
// Console.cpp: implementation of the CConsole class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "test002.h"
#include "Console.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
BOOL CConsole::IsExistent = FALSE;
CConsole::CConsole()
{
if (IsExistent)
return;
AllocConsole();
Attach(300, 80);
IsExistent = TRUE;
}
CConsole::CConsole(LPCTSTR lpszTitle, SHORT ConsoleHeight, SHORT ConsoleWidth)
{
if (IsExistent)
return;
// hStda = GetStdHandle(STD_OUTPUT_HANDLE);
AllocConsole();
SetConsoleTitle(lpszTitle);
Attach(ConsoleHeight, ConsoleWidth);
IsExistent = TRUE;
}
void CConsole::Attach(SHORT ConsoleHeight, SHORT ConsoleWidth)
{
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;
}
CConsole::~CConsole()
{
if (IsExistent)
{
FreeConsole();
IsExistent = FALSE;
}
}
DWORD CConsole::printf(CString message)
{
DWORD dwWritten=0;
if(WriteConsole(hStd,message,message.GetLength(),&dwWritten,NULL))
return dwWritten;
return 0;
}