我一直好奇,所以我跟着Bo Persson's answer提供和拼湊一些代碼的鏈接。要使用它,只需在main
中定義一個UseConsole
對象。
UseConsole.h:
class UseConsole
{
public:
UseConsole();
~UseConsole();
private:
bool m_good;
};
UseConsole.cpp:
#include <windows.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <iostream>
#include <fstream>
#include "UseConsole.h"
// The following function is taken nearly verbatim from
// http://www.halcyon.com/~ast/dload/guicon.htm
void RedirectIOToConsole()
{
int hConHandle;
long lStdHandle;
FILE *fp;
// redirect unbuffered STDOUT to the console
lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen(hConHandle, "w");
*stdout = *fp;
setvbuf(stdout, NULL, _IONBF, 0);
// redirect unbuffered STDIN to the console
lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen(hConHandle, "r");
*stdin = *fp;
setvbuf(stdin, NULL, _IONBF, 0);
// redirect unbuffered STDERR to the console
lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen(hConHandle, "w");
*stderr = *fp;
setvbuf(stderr, NULL, _IONBF, 0);
// make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
// point to console as well
std::ios::sync_with_stdio();
}
UseConsole::UseConsole()
{
m_good = !!AttachConsole(ATTACH_PARENT_PROCESS);
if (m_good)
RedirectIOToConsole();
}
UseConsole::~UseConsole()
{
if (m_good)
FreeConsole();
}
通常一個應用程序或者是一個控制檯應用程序或窗口應用程序 - 不可能兼顧。我希望你找到有這方面經驗的人,因爲這很少見。 –