Using a Windows MessageBox to display Console results

vegaseat 0 Tallied Votes 865 Views Share

I borrowed this from C#, where you can easily send output, that normally goes to the ugly black console window, to a nice looking Windows MessageBox with an OK button to close after you read your results. You can accumulate your output in a string to send to one message box, or even use different message boxes. Experiment with it!

// use a message box to display console output
// compile as GUI
// tested with Pelles C     vegaseat    15jun2007

#include <windows.h>
#include <string.h>
#include <stdlib.h>

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{

  char output[1000];
  char st[20];
  int number, sum;
  
  for ( number = 2; number <= 1000; number += 2 )
    sum += number;

  // convert int to string
  // Pelles C uses _itoa() instead of itoa()
  _itoa(sum, st, 10);
  // build up output string
  strcpy(output, "The sum of even integers from 2 to 1000 is ");
  strcat(output, st);

  // now send the result to a Windows message box
  MessageBox(NULL, output, "Show console output in a MessageBox", MB_OK);
  return 0;
}
// use a message box to display console output
// compile as GUI
// tested with Pelles C     vegaseat    15jun2007

#include <windows.h>
#include <string.h>
#include <stdlib.h>

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{

  char output[1000];
  char st[20];
  int number, sum;
  
  for ( number = 2; number <= 1000; number += 2 )
    sum += number;

  // convert int to string
  // Pelles C uses _itoa() instead of itoa()
  _itoa(sum, st, 10);
  // build up output string
  strcpy(output, "The sum of even integers from 2 to 1000 is ");
  strcat(output, st);

  // now send the result to a Windows message box
  MessageBox(NULL, output, "Show console output in a MessageBox", MB_OK);
  return 0;
}
FlIrishman 0 Newbie Poster

I've tried this technique using Visual Studio C++ 2008 and all I get is a BEEP when the message box should be displayed. I've been working on this for some time now and cannot figure it out?

<<snip>>

nagendra_rao 0 Newbie Poster

@[vegaseat]

Thanks!! It was really helpful!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.