Hi to all. I want to redirect console streams to cin,cout and cerr. (its a gui application) Well, I have written this class wich do this but when use cin, cout works no more.
GetLastError says me INVALID_HANDLE VALUE
Can you explain me how fix this ? Thanks
Kconsole.h
class Kconsole
{
public:
Kconsole();
~Kconsole();
void CreateConsole( void );
void CloseConsole ( void );
private:
HANDLE hin;
HANDLE hout;
HWND hwnd;
bool closed;
bool err;
ofstream n_cout;
ofstream n_cerr; // new streams
ifstream n_cin;
streambuf* old_cout;
streambuf* old_cerr; // old streams
streambuf* old_cin;
};
Class method:
void Kconsole::CreateConsole( void ){
// create a console window
int ok = AllocConsole();
if ( ok == 0 ) // check console creation
{
this->err = true;
return;
}
// redirect cout to console window
this->old_cout = cout.rdbuf();
this->n_cout.open("CONOUT$");
cout.rdbuf( this->n_cout.rdbuf() );
// redirect cerr
this->old_cerr = cerr.rdbuf();
this->n_cerr.open("CONOUT$");
cerr.rdbuf( this->n_cerr.rdbuf() );
// redirect cin
this->old_cin = cin.rdbuf();
this->n_cin.open("CONIN$");
cin.rdbuf( this->n_cin.rdbuf() );
//// set title
SetConsoleTitle("Console");
this->hwnd = GetConsoleWindow();
//
//// get handles
this->hin = GetStdHandle(STD_OUTPUT_HANDLE);
this->hout = GetStdHandle(STD_OUTPUT_HANDLE);
return;}
Main function
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,intnCmdShow){
// All application initialization as RegisterClass, CreateWindow...
// CreateConsole Call
cout << "\nTest string"; // ok, writes this in opened console
int n = 0;
cin >> n; // ok, get typed number
n++;
cout << "\n test finished"; // dont outputs nothing to console
// here GetLastError says INVALID_HANDLE_VALUE
cerr << "\n testing cerr" // cerr outputs in console " test finished" and "testing cerr"
}