Display message in windows dialogue box using "cout" - C++

22,315

Solution 1

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.

Solution 2

C++ streams work with console or file streams. Windows work on a more or less completely different paradigm, so the cout context isn't really a good one for working with this. You could probably completely mash up something that would end up more or less working, and looking more or less similar to this syntax, but it's not really worth it when you can just do:

MessageBox( NULL, message, "", MB_OK );

See the full docs on MessageBox for more info.

Solution 3

By including sstream, you can use std::ostringstream and build a message using the iostream library. You can then call .str().c_str() and get a char * to pass to MessageBox.

Solution 4

When confronted with this in the past, I've used a stringstream along with a manipulator that displays the current contents of the stringstream using MessageBox:

#include <windows.h>
#include <sstream>
#include <ostream>

std::ostream &MessageBox(std::ostream &s) {
    std::ostringstream *st = dynamic_cast<std::ostringstream *>(&s);
    if (NULL != st)
        ::MessageBox(NULL, st->str().c_str(), "", MB_OK);
    return s;
}

To use this, the syntax looks a fair amount like using cout, but with MessageBox replacing std::endl. For example:

std::ostringstream stm;
stm  << " blah blah blah. Value: " << 1213.1231 << MessageBox;

Edit: mostly for fnieto. In this case, the downcast really is necessary. The reason is fairly simple: a typical inserter receives and returns a reference to an ostream:

std::ostream &operator<<(std::ostream &os, T const &t) { 
    // code here to insert t into os, then return os;
}

This takes the original stringstream object and silently (and safely) casts it up to a simple ostream. That's fine in itself, and works fine for most inserters and manipulators, because they only interact with the ostream interface themselves.

This manipulator, however, is a bit different -- it uses the str() member, which ostream doesn't define at all. For our call to str() to resolve and compile, we have to convert the ostream & to an ostringstream &, so the compiler is aware that the object we're working with really will have a str() member.

To eliminate the downcast, we'd really only have one choice: make its parameter an ostringstream &. That would work as long as we never chained operators:

my_stream << x;
my_stream << MessageBox;

but trying to chain those would fail:

// should be equivalent:
my_stream << x << MessageBox;

Worse, the compiler's error message will probably try to tell the user something about std::basic_ostream<char>::str(), which isn't mentioned in the user's code at all. Worse still, most people are sufficiently accustomed to chaining or not giving identical results that it would probably take them a while to even figure out why the code sometimes worked fine, and other times failed to compile, with a completely indecipherable error message.

Solution 5

No simple way anyway.

The c in cout stands for console, so you're probably out of luck.

If it's just the syntax you're looking to copy, then you could write your own stream class that creates a message box under the hood and displays it.

Share:
22,315
CheeseConQueso
Author by

CheeseConQueso

facebook.com/CheeseConQueso - Facebook pocketband.net - uLoops/PocketBand grooveshark.com/CheeseConQueso - Grooveshark

Updated on November 26, 2020

Comments

  • CheeseConQueso
    CheeseConQueso over 3 years

    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?

  • CheeseConQueso
    CheeseConQueso over 14 years
    yeah that's what i suggested to this person, but they want cout to be part of the ordeal for some obscure reason
  • Clifford
    Clifford over 14 years
    He only wants cout-like syntax, not cout itself. An std::ostringstream can be used to build the string to pass to the windows object. As per Stephen Newell's answer.
  • Bill
    Bill over 14 years
    They want cout specifically, or they want a stream similar to cout?
  • Brian
    Brian over 14 years
    Using this technique combined with Jerry COffin's technique will probably yield a program which, without changes to anything but the initialization, successfully turns cout into a messagebox. Also, it will suck (but might make this person happy).
  • CheeseConQueso
    CheeseConQueso over 14 years
    im 90% sure that they want cout specifically. it is an instructor and he is probably going to by the book. they don't want the students being able to access the command prompt
  • Glen
    Glen over 14 years
    @Clifford, yes, I understand he might only want the stream syntax. That's why I mentioned using his own stream class that calls the message box functionality under the hood. maybe I wasn't clear enough....
  • jmucchiello
    jmucchiello over 14 years
    Have him log in here so we can tell him IT IS NOT POSSIBLE using cout.
  • Fernando N.
    Fernando N. over 14 years
    @jmucchiello, don't go so fast if you are not positive and have a look here: stackoverflow.com/questions/1730427/…
  • David Rodríguez - dribeas
    David Rodríguez - dribeas over 14 years
    In most OS you can redirect standard input/output to another file or pipe, and if that is done, then it is no longer 'console out', but just plain 'standard output'
  • CheeseConQueso
    CheeseConQueso over 14 years
    the first thing it told me was to include stdafx.h.... after including that, I got bunch of errors that I don't have access to until that person is back to test some new things with me again
  • Fernando N.
    Fernando N. over 14 years
    Those problems don't have anything to do with this code but with "precompiled headers" options in your project.
  • Jason D
    Jason D over 14 years
    One note here: The following only shows one line per block of text between "endl"s. Unless I explicitly terminate the output withendl, or call cout.flush() the very last block isn't displayed. (e.g cout << "abc" << endl << "bah"; won't display "bah" without calling flush) Interestingly you can get a multiline display by passing "\r\n" as literal text. . .
  • Fernando N.
    Fernando N. over 14 years
    @Jason D. Right, it should have a overwritten destructor flushing remaining data before exit. By the way, <<std::endl is equivalent to do <<"\n"<<std::flush so you can break the line with \n.
  • CheeseConQueso
    CheeseConQueso over 14 years
    got it to work... thanks... the problem wasn't in the code, it was the way the project was set up
  • CheeseConQueso
    CheeseConQueso over 14 years
    there is also a command to suppress the cmd.exe from showing .... i forgot where i found it, but it would help in here. also, if this whole thing could be made as a write-protected include file to be given to his students, that would be an epic win