Creating and Using Forms

Because Visual C++ .NET now has a GUI designer, you no longer have to construct GUI code by hand. This section will show you how to create and use forms using Visual Studio .NET 2003.

Creating a Simple Form

The following exercise shows you how to create and display a simple form.

  1. Start Visual Studio .NET, and open the New Project dialog box. Choose the .NET subfolder under the Visual C++ Projects entry, and create a new Windows Forms Application project named CppForm. Visual Studio .NET will display a form designer window like the one shown in the following figure.

    click to expand

  2. Compile and run the code. A window will be displayed, as shown in the following figure.

    You can see how the form has all the attributes of a window: it has a title bar with a caption and a system menu button on the left; it has Minimize, Maximize, and Close buttons; and you can resize it. The size and caption are set by properties in the C++ code. Right-click the form displayed in the designer, and choose View Code from the context menu. This will display the code for Form1.h. If you examine the code in the InitializeComponent function, you’ll see where the Size and Text properties are set. You’ll see later in the chapter how to use the Properties editor to change these properties.

  3. Click the Close button—the one marked with an X on the far right of the title bar—to close the window. This terminates message processing, and closes the window.

start sidebar
What’s a Message Loop?

If you don’t know how a Windows application works, here is a quick introduction.

A message loop is at the heart of every Windows application, providing the “pump” that drives the execution of the program. The parts of a Windows application, such as the forms, buttons, and scroll bars, communicate with each other, with other applications, and with the system by passing messages. In the world of Windows programming, a message is a small packet of data that is sent to a component to tell it something has happened. These somethings, called events, could include a timer going off, a key being pressed on the keyboard, or the user clicking a button. A message is a structure that describes an event, and Windows delivers the message to the appropriate application, placing it in the application’s message queue.

A tremendous number of events are delivered to a Windows application all the time, even when nothing much appears to be happening. At the heart of the application sits the message loop, a tight loop of code that removes one message at a time from the message queue and sends each off to the correct part of the application for processing.

In prehistoric times, when the only tools programmers had for writing Windows programs were a C compiler and a copy of the Windows SDK (Software Development Kit), you had to code the message loop manually and understand the architecture behind message processing. Now we have development frameworks—such as MFC and the .NET Framework—that do all the housekeeping for you, so you don’t need to get into the details of how message processing happens. You can if you want to do advanced and clever things, but you don’t have to for the vast majority of applications.

So when you want to run a form as the GUI for your application, you need to start a message loop so that the form can process messages. You do so using the Application::Run function, which has the effect of both starting a message loop and displaying the form.

The message loop keeps running until it receives a quit message, which can be sent from application code or by the operating system as a result of the user physically closing the window. In either case, the message loop terminates, the window closes, and the application exits.

end sidebar

Using Form Properties

Now that you’ve mastered the basics of displaying a form, let’s move on to see how you can affect the way the form looks and behaves. When you examine the code in Form1.h, you’ll see that the form is represented by a class that inherits from System::Windows::Forms::Form. You use this class as the base class whenever you want to create a form.

The Form class has a large number of properties and methods, the most important of which are summarized in the following table.


Method or Property?




Gets or sets a reference to the button control that corresponds to the user pressing Enter.



Activates the window, bringing it to the front of the application’s collection of windows.



Gets the currently active form for this application, meaning the one at the front of the application’s collection of windows.



Gets or sets a Boolean value indicating whether the form adjusts its size to fit the height of the font used on the form and scales its controls accordingly. The default is true.



Gets or sets a value indicating whether the form displays scroll bars when controls fall outside the displayable area. The default is true.



Gets or sets a reference to the button control that corresponds to the user pressing Esc.



Gets or sets the size of the client area of the form. (The client area is the portion of the form that excludes the title bar and borders.)



Closes the form and frees any resources the form has used.



Gets or sets the location of the form on the Windows desktop.



Gets or sets the border style of the form. The default is FormBorderStyle::Sizeable.



Gets or sets a Boolean value indicating if the form is to display a Help button on the title bar. The default is false.



Gets or sets the icon associated with the form.



Gets or sets a Boolean value that indicates if the form is displaying a Maximize box on the title bar. The default is true.



Gets or sets a reference to the menu that is displayed on this form.



Gets or sets a Boolean value that indicates if the form is displaying a Minimize box on the title bar. The default is true.



Holds the collection of child forms owned by this form, if any.



Sets the location of the form on the desktop.



Shows the form as a modal dialog box.



Gets or sets a Boolean value, which is true if the form is to be shown in the Windows taskbar. The default is true.



Gets or sets the form’s size.



Determines how (or even whether) the sizing grip is shown at the lower right of the form. The default is SizeGripStyle::Hide.



Gets or sets a Boolean value, which is true if the form is a top-level window, meaning that it has no parent other than the Windows desktop. The default is true.



Gets or sets a Boolean value, which is true if the form is a topmost window, meaning it is always displayed on top of other windows, even when it doesn’t have the focus. The default is false.



Gets or sets the form’s window state, which determines how the form is displayed—minimized, maximized, or normal. The default is FormWindowState::Normal.

The Form class also has a very large number of methods and properties that it inherits from its base classes, which are shown here:

 Object  MarshalByRefObject  Component  Control  ScrollableControl  ContainerControl  Form 

Notice especially the Component class, which forms the basis for all components that can be used with forms, and Control, which provides the base class for all visual components. All the base classes between them provide Form with approximately 110 properties, 180 methods, and 70 events! There are far too many to list here, so I suggest that you consult the .NET Framework documentation for more details. When I use inherited properties in the exercises or examples in this chapter, I’ll tell you which base class they come from.

Although you can interact with the form’s properties in code, the designer provides a Properties editor that gives you graphical access to all the most frequently used properties.

The following exercise will show you how to use the Properties editor to edit the properties of a form so that you can make it appear where and how you want.

  1. Continue with the previous application, making sure that the design window is displayed. If the design window is not open, click the Form1.h file in Solution Explorer. You’ll see that the form header file has a different icon from the other header and source files because it is the file that contains the definition of the form, and it’s the file that is used by the designer.

    Right-click the form, and choose Properties from the context menu. The Properties editor will be displayed. Select the Text property, and change its value to give a suitable caption to the form, as shown in the following figure.

    The Text property is inherited from Control, and it’s being used here to set the text associated with the control. Many controls have some notion of an associated piece of text. In the case of an edit control, it’s the text in the control; in the case of a button, it’s the legend on the button. In the case of a form, it’s the title displayed on the title bar of the form.

    If you rebuild and run the code, you’ll see that the form now displays a caption.

  2. The form border is represented by the FormBorderStyle property, which takes its value from the FormBorderStyle enumeration. The default border style is FormBorderStyle::Sizeable, which provides a simple border whose outline you can drag to change the size of the form. Use the Properties editor to change the border style to Fixed3D.

  3. Compile and run the code, and you’ll see that the border style has changed and you can no longer resize the window, as shown in the following figure.

    Experiment with other Form properties to change the look and feel of the form.

Form Relationships

Any form can create other forms—think of displaying a dialog box—and by default, forms will be independent of one another so that you can minimize them and close them separately. There will be a parent/child relationship between the forms, but apart from that relationship, they are independent. Top- level forms, which are usually used for an application’s main window, either do not have a parent form or have the desktop as a parent.

It’s also possible for one top-level form to be the owner of another top-level form, in which case there is a relationship between the two forms such that:

  • The owned form is minimized, maximized, and hidden along with its owner.

  • The owned form is closed when the owner form is closed.

  • The owned form never displays behind the owner form.

Think of the Find And Replace dialog box in Microsoft Word. This window appears when you want to find something in the document, and it hovers over the Word window until you close it. If you minimize Word, the dialog box is minimized, and it disappears when you close Word.

Placing Controls on the Form

Now that you know how to create forms and set their properties, let’s examine how to add controls to a form. The following exercise will walk you through adding two buttons to the form, and the same procedure can be applied to many other controls.

  1. Continue with the same Windows Forms project that was used in the previous two exercises.

  2. Make sure that the designer window is open, and open the Toolbox. If the Toolbox is not already visible, you can open it by using the Toolbox item on the View menu or by pressing Ctrl+Alt+X. If the Windows Forms tab is not open on the Toolbox, select it. Selecting this tab will display all the controls that can be used with Windows Forms.

    Click the Button entry in the Toolbox, and drag it onto the form. When you release the mouse button, you will see a button appear on the form.

  3. Select the button, and use the Properties editor to set its Name to btn1, its Text to OK, its Size to 70,25, and its Location to 130,225. The coordinates for Location are in pixels, relative to the upper-left corner of the form containing the button. If you examine the code in Form1.h and look at the InitializeComponent function, you will see that code has been added to create and set up the button. The designer changes the code in the InitializeComponent function as you edit the form, so you should be very careful about editing InitializeComponent yourself.

    Notice how the button has been added to the Controls property of the form. Every container (such as a form) has a Controls property that contains references to all the controls currently hosted by the form. By adding a control to the collection, the form will display it and will treat it as an owned window.

  4. Add a second button to the form, and name it btn2. Make it display Cancel for the text, and make the size the same, but change the Location so that this one displays at (210,225).

    Compile and run the code, and you should see two buttons displayed on the form, as shown in the following figure.

Handling Events

It isn’t much use placing buttons on a form unless you can make them do something, so let’s take a look at how to handle the events that are fired by controls. The .NET event mechanism was covered in Chapter 14, so you might review that material now if you want to refresh your memory.

To handle an event, you need to create an event handler function and attach it to the event source. In Chapter 14, you saw how to do this with custom event source and receiver classes, and now I’ll show you how to do it with standard event sources in the form of controls.

The following exercise, which follows on from the last one, shows you how to add event handlers for the buttons on the form.

  1. Continue with the project from the previous exercise. The form currently contains two buttons, and you’re going to add handlers for the Click events that are raised when the buttons are clicked.

    Select the OK button, and bring up the Properties editor. Click on the Event button at the top of the Properties editor window—the button with a lightning bolt as a symbol—and the editor will show the events associated with the button. Find the Click event in the left- hand column, and double-click in the blank space to the right of it. The name btn1_Click will be inserted into the space, and a function with the same name will be added to the code.

  2. This function is called when the button is clicked, and just to prove that the handler is called, add a line to display a message box, as shown here:

    private: System::Void btn1_Click(System::Object * sender, System::EventArgs * e) { MessageBox::Show(S"It worked!", S"Message..."); }

    The MessageBox class is part of the Forms namespace, and its one Show method is used to display a standard Windows message box. Show has a dozen overloads that take different combinations of arguments, and the one I’m using specifies only the message and title. This message box will display without an icon and with a single OK button.

  3. If you look in InitializeComponent, you can see how the button has been made aware of the handler.

    this->btn1->Click += new System::EventHandler(this, btn1_Click);

    From the discussion of events in Chapter 14, you’ll recall that event handlers are connected with event sources by delegates. There are several different event handlers associated with controls (we’ll meet some of them later in the chapter), but the delegate used for controls that don’t pass back any data is called EventHandler, and this event delegate passes back a plain EventArgs object.

    So, to connect an event handler to the button object, a new EventHandler is created, which is passed a pointer to the object that is going to handle the event and the address of the event-handling function within the object. In this case, the event is being handled within the form object, so the this pointer is passed for the first argument and the address of the btn1_Click function as the second.


Remember that in C++ the name of a function, when used on its own without parentheses, evaluates to the address of the function.

The event handler is registered with the source by using the += operator to link the handler to the button’s Click event.

  1. Try building and testing the application. You should see a message box like the one shown in the following figure when you click OK.

    Note that the message box is modal: you can’t return to the application until you’ve sent the message box away by clicking OK.

  2. Try adding a similar handler for the Cancel button.

Microsoft Visual C++  .NET(c) Step by Step
Microsoft Visual C++ .NET(c) Step by Step
ISBN: 735615675
Year: 2003
Pages: 208 © 2008-2017.
If you may any questions please contact us: