CIS Logo SVC Logo

   Computing & Information Systems


Schoology Facebook        Search CIS Site      Tutorials

Software Design Using C++

Dialog-Based Interface with Visual C++ .NET

A Simple Example

1) Overview

In this example you will use AppWizard in Visual C++ .NET to create a Windows application that finds the area of a rectangle. The user will fill in the length and width in two boxes (called edit controls), click on a Calculate button, and the resulting area will then appear in a box labeled area. Examine this picture of the user interface to see what we are aiming to produce.

2) Starting AppWizard

Use this screen shot as a guide for the items in this paragraph. (Note that many of the later screen shots will be provided as links within the text. Click on these if it helps you to see what is being discussed here in words.) Select File, New, Project, Visual C++ Projects. Click on MFC Application. Fill in area as the project name. You can click on the appropriate radio button to add this project to your existing solution (if any) or you can create a new solution. (Recall that a solution is a collection of projects. In Visual C++ 6.0 a solution was called a workspace. It is often useful, for example, to place all of your projects for a given course into the same solution. This keeps them grouped together.) Finally, click on OK.

You are now in the MFC Application Wizard, where some choices must be made about the application to be created. Under Application Type, select Dialog based. Under User Interface Features, fill in "Area of a Rectangle" as the Dialog title. Windows XP users should uncheck Common Control Manifest found under Advanced Features. Then click on Finish. The AppWizard generates the code and associated files needed for the application as outlined thus far.

Note that the Statically Linked option for using the MFC (Microsoft Foundation Class) library is sometimes useful instead of the Shared DLL option. This is especially true when you want to use your .exe file under more than one version of Windows. Since you cannot be sure which DLL files will be available, it is safest just to statically link in whatever code is needed. That way your program is not dependent on these DLL files. It will make your .exe file larger but more portable.

3) Adding Controls to the User Interface

It is useful to have several windows on the screen. Use View, Solution Explorer if the Solution Explorer is not already visible on the screen. Similarly, use View, Class View as well as View, Resource View to get these windows on the screen. Lastly, use View, Properties Windows to make sure that one is also visible. Click on the Resource view tab. If need be, click on the + in front of area and area.rc to expand what you see. Also click on the + in front of "Dialog". Double click IDD_AREA_DIALOG under the expanded Dialog folder.

This will bring up a window where you build your dialog-based user interface visually. Note that your Dialog form automatically contains an OK button, a Cancel button, and a TODO string. Delete these items by clicking on each and pressing the Delete key in each case.

If the Toolbox window is not showing, use View, Toolbox. Right click on the middle of the toolbox and see that Show All Tabs is checked. Click on Dialog Editor. You should see a list of items that can be added to your dialog: Button, Check Box, Edit Control, etc. If you do not see this list, right click on the Toolbox, select Customize Toolbox, and click on Reset and then on Yes.

Note that you can drag the lower right corner of your application's dialog window to resize it. A window that is about 5 inches wide and 4 inches high should work nicely for our application.

Drag a group box control from the Toolbox to the upper left corner of your application window. Move the group box around until it fits nicely in this corner. You do this by clicking on the group box and then moving the mouse to an edge of the group box until you get a 4-headed arrow pointer. You can then drag the control. Also drag the black squares at the edges of the group box (get the mouse pointer on one so that it changes to a 2-headed arrow) so that the group box essentially fills the top half of your application window. Click on the group box to be sure that it is selected, then go to your Properties window and change the caption to "Fill in the length and width:". (Although this field already contains the word "static", you can click on it and type in the new caption.) Check this image of the form to see how it should look at this point.

Drag a Static Text control from the Toolkit and place it in the left quarter of the group box. Move this text control so that it fits reasonably. With this Static Text control selected (click it to be sure), change the caption to "Length:". Resize the Static Text control as needed so that the caption shows reasonably.

Drag an Edit control onto your dialog form, just to the right of your Static Text control labeled "Length:". Move the edit control so that it lines up with this text control, but make sure that the 2 controls do not overlap. (Click on each in turn and watch where their edges are.) Then click on the edit control and change the ID field to "IDC_EDIT_LENGTH". Check this picture of the results so far. Note that an edit control is a place where the user can type in data and where the application can display data.

In a similar way, place a Static Text control in the left half of the group box (below the previous static text control) and change its caption to "Width:". Just to the right of it place an Edit Control and change its name to "IDC_EDIT_WIDTH". Be sure that none of the 4 controls overlaps with another one.

Much like before, place another group box control onto your application's window, but this time move and resize it to fill the bottom half of the window. Change the caption of this group box to "Click Calculate button to get the area:". Drag a Button control from the Toolkit to top middle of the new group box. In the Properties window, with the button selected, change the ID field to IDC_BUTTON_CALCULATE and the caption to "Calculate". Here is an image of the results.

Place a Static Text control on the bottom left of this group box. Change its caption to "Area:". Place an Edit control just to the right of this text, just under the Calculate button. Change the ID of this edit control to IDC_EDIT_AREA. Refer to this image of the form to see how it looks at this point.

Use File, Save All to make sure that your work has been saved. We are now done with visually designing the user interface. The primary remaining steps are these: to associate some variables with the edit controls and to attach some code to the Calculate button.

4) Adding Variables Associated with the Controls

Variables are used to contain data that the user places in the edit controls. Variables can also be used to hold data that we wish to place into an edit control (or other control). Find Class View. Right click on CAreaDlg and select Add, Add Variable. You should now be in the Add Member Variable Wizard. Check the Control Variable box and make sure that the Control ID box contains IDC_EDIT_LENGTH, the ID of our edit control for the length. (Use the pull-down to change this ID if need be.) Change the Category entry to Value and the Variable Type to float. Make sure that the Access entry says public. (We want our new variable to be a public field of the CAreaDlg class.) Fill in m_EditLength as the name of the variable. Click on Finish.

In the same way, add a variable to CAreaDlg for the Edit control having the ID of IDC_EDIT_WIDTH. Name the variable m_EditWidth and have it also be a float. Then add a float variable named m_EditArea for the control with ID IDC_EDIT_AREA. Do not associate a variable with the Calculate button. Do File, Save All.

5) Attaching Code to the Button

Right click on the Calculate button on your form. Select Add Event Handler. This will show you the Event Handler Wizard. Make sure that the correct class, CAreaDlg, is selected in the Class list. IDC_BUTTON_CALCULATE should already be filled in as the Command name. Under Message type select BN_CLICKED. (The suggested function handler name will be fine. This function will be set up to contain the code that will be executed when the user clicks on the Calculate button.) Click on the button labeled Add and edit. This will bring up the appropriate code file with an outline of the above function. Type the following code between the braces for this function:

m_EditArea = m_EditLength * m_EditWidth;

Then use File, Save All to save your work. Note that the UpdateData function is used to copy data between your variables and the on-screen controls. UpdateData(TRUE) copies the data from the controls (edit controls in this case) to the variables. UpdateData(FALSE) copies data in the reverse direction, from the variables to the controls. In this case, since the second line has put a new value into m_EditArea, it is this value which gets copied into the area edit control. (The length and width values are also copied into their controls, but this doesn't change anything.)

6) Compiling and Running Your Application

Select Build, Build area. (If Build area is not listed, it may because some other project is currently active. You can fix this by clicking on the main area folder in either the Solution Explorer or Resource View. Then use Project, Set as Startup Project.) Any error messages or warnings will be shown in an Output window. If there are errors, fix them. If not, you can run your application by using Debug, Start without Debugging. Just fill in a length and width, click on the Calculate button, and you should have an area shown in thei user interface. Of course you can do this as many times as desired. When ready to quit, click on the x close button in the upper right corner of the application.

Once your program is running correctly, you can switch from the Debug version to the Release version. Select Build, Configuration Manager. Select Release in the Active Solution Configuration box (as opposed to Debug). Then click on Close. Rebuild your project by using Build, Build area. The compiled program (the area.exe file) will probably be smaller in size and run faster as it does not include the code needed for running the debugger. The .exe file for the Release version is located in the Release directory, while the one for the Debug version is in the Debug directory -- both located inside the project directory.

7) For Further Practice (Optional)

If you like you can add a Clear button to the above application. Clicking on it should place zeros into the 3 edit controls.

Another possibility would be to design a calculator application. It could be designed with an accumulator edit control and a value edit control (where the user could place a new number). There could be buttons for add, subtract, multiply, and divide. Subtract, for example, would subtract the number in the value edit control from the value in the accumulator and place the answer back into the accumulator. The other arithmetic operations would work in a similar manner.

A different calculator design would follow the stack algorithm for evaluating a postfix expression. Here you could have an edit control showing the top of stack item and an edit control for entering a new number. You could have a button to click on to push the new number onto the stack as well as buttons for +, -, *, and /. For example, the + button should cause 2 items to be popped from the stack, the sum computed, and the result pushed onto the stack.

A somewhat better design for a postfix calculator would have an edit control where you could place the entire postfix expression all at once. Another edit control would be needed to show the value of the expression. A third edit control could be used to display any error message. You would need a Calculate button and might like to have a Clear button for clearing out the edit controls.

You could also create a calculator that would accept an ordinary infix expression, such as (4 + 12) / 3, and display its value. This would involve first converting the infix expression to postfix, and then using the above stack algorithm to find the value of the postfix expression. Since the sample conversion code uses the STL (standard template library) for creating a stack, you would probably want to use an STL-based stack for the evaluation algorithm as well.

Related Item

Dialog-Based Interface with Visual C++ 6.0

Back to the main page for Software Design Using C++

Author: Br. David Carlson with contributions by Br. Isidore Minerd
Last updated: August 27, 2009