Building Graphical User Interfaces (GUIs)
Using the Windows Application Programming Interface (API)


All of these examples assume that Microsoft Visual C++ 2010 or 2012 is the compiler being used.

Exercise 1: A very simple first GUI program

There is a tradition among C programmers that your first program should do nothing but print "Hello, world" on the screen. Here you will follow that tradition.

  1. If you have not already created the FirstWinApp project then click back on your browser and click the link Creating Projects in Visual Studio for GUI applications and follow the instructions for creating the project for exercise 1.

  2. Add a .cpp source file to the project. (Right click Source Files and select Add->New item. In the dialog box select .cpp file and give it a name like FirstWinAppMain.cpp.

  3. Copy and paste the following text into the .cpp file changing John Doe to your name:
    #include <windows.h>
    
    int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    	LPSTR lpCmdLine, int nCmdShow)
    {
    	MessageBox(NULL, "Hello, world!", "Note-John Doe", MB_OK | MB_ICONEXCLAMATION);
    	return 0;
    }
    		
  4. Compile and run the application. You should see a small message box like the one below:



Now try modifying this "Hello, World" code:
  1. Change the text of the message and note that the message box always resizes to accomodate the text.
  2. Try inserting the '\n' character to create multi-line messages.
  3. Try different combinations for the fourth argument to the MessageBox function call
    To indicate the default button, specify one of the following values.
For more information about the various flags and use of MessageBox check the MSDN MessageBox link.

This may not seem like much of an exercise, but you have taken a big step forward. Now you know how to display a message box any time you need to in a Windows GUI program.