c++ - Redirecting cout to the new buffer that created with winapi -
i'm trying print new screen buffer i've create winapi it's going old buffer , doesn't show on screen, possible, redirecting cout
new screen buffer created using winapi?
#include <iostream> #include <windows.h> int main() { handle stdbuf, nbuf; dword numberofchars; stdbuf = getstdhandle(std_output_handle); nbuf = createconsolescreenbuffer(generic_write, 0, null, console_textmode_buffer, null); setconsoleactivescreenbuffer(nbuf); setstdhandle(std_output_handle, nbuf); // showing on screen writeconsole(nbuf, "second buffer", 13, &numberofchars, null); // going first buffer std::cout << "second buffer cout" << std::endl; sleep(3000); setconsoleactivescreenbuffer(stdbuf); closehandle(nbuf); int = 0; std::cin >> a; return 0; }
yes, it's possible. no, it's not entirely trivial.
the basic problem simple: there existing stream buffers talk named file, (probably) not existing 1 talk console. work, need 1 talks console. here's simple starting point:
class outbuf : public std::streambuf { handle h; public: outbuf(handle h) : h(h) {} protected: virtual int_type overflow(int_type c) override { if (c != eof) { dword written; writeconsole(h, &c, 1, &written, nullptr); } return c; } virtual std::streamsize xsputn(char_type const *s, std::streamsize count) override { dword written; writeconsole(h, s, count, &written, nullptr); return written; } };
[note: incomplete--it console output fine, if (for example) copy or assign it, bad things may happen--the usual rule of 0/3/5 applies.]
once have stream buffer writes output console, connecting cout
pretty trivial:
console_stream_buffer buff(nbuf); std::cout.rdbuf(buff); std:cout << "bleh"; // should go console `nbuf`.
here's quick demo using it:
int main() { handle h = createconsolescreenbuffer(generic_write, 0, null, console_textmode_buffer, null); handle original = getstdhandle(std_output_handle); // create our stream buffer object outbuf ob(h); // write original buffer std::cout << "first console"; // set cout go second buffer std::cout.rdbuf(&ob); // write std::cout << "second console"; // display second buffer setconsoleactivescreenbuffer(h); // show second buffer few seconds: sleep(5000); // restore original buffer setconsoleactivescreenbuffer(original); }
you could, of course, write stream buffer allocates console screen buffer itself, if wanted to. left separate now, depending on how you're using things, may make more sense combine them (and include activate
member calls setconsoleactivescreenbuffer
well). none of relevant original question though, i'll leave now.
Comments
Post a Comment