Can a windows message box be display using the cout syntax?
I also need the command prompt window to be suppressed / hidden.
There are ways to call the messagebox function and display text through its usage, but the main constraint here is that cout syntax must be used.
cout << "message";
I was thinking of invoking the VB msgbox command in the cout output, but couldn't find anything that worked.
Any ideas?
First thing you should take into account is that MessageBox stops the thread until you close the window. If that is the behavior you desire, go ahead.
You can create a custom streambuf and set it to std::cout
:
#include <windows.h>
#include <sstream>
#include <iostream>
namespace {
class mb_streambuf : public std::stringbuf {
virtual ~mb_streambuf() { if (str().size() > 0) sync(); }
virtual int sync() {
MessageBoxA(0, str().c_str(), "", MB_OK);
str("");
return 0;
}
} mb_buf;
struct static_initializer {
static_initializer() {
std::cout.rdbuf(&mb_buf);
}
} cout_buffer_switch;
}
int main()
{
std::cout << "Hello \nworld!"; // Will show a popup
}
A popup will be shown whenever std::cout stream is flushed.