Home

The Forms of an Application

 

Fundamentals of a Form

 

Introduction

The form is the most fundamental object used in an application. By itself, a form does nothing. Its main role is to host other objects that the user uses to interact with the computer:

Form 1

Form Creation

There are various ways you can get a form to your application:

  • If you create a Windows Forms Application, it creates a starting form for you
  • After starting an empty project or a Windows Forms Application, you can add a form to it. To do this, on the main menu, you can click Project -> Add New Item... Select Windows Form. Give it a name and click OK
  • You can dynamically create a form and add it to your application.

In Lesson 2, we saw that a was based on the Form class that is defined in the System::Windows::Forms namespace created in the System.Windows.Forms.dll assembly. Therefore, if you start an application from scratch and you want to use a form in it, you can include the System.Windows.Forms.dll library to your application. To refer to a form, you can include the System::Windows::Forms namespace in your application.

As seen in Lesson 2, to create a form-based application, you can derive a class from Form. Here is an example:

#include <windows.h>

#using <System.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Windows::Forms;

public ref class CExercise : public Form
{
public:
    CExercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
    }
};

int APIENTRY WinMain(HINSTANCE hInstance,
		     HINSTANCE hPrevInstance,
		     LPSTR lpCmdLine,
		     int nCmdShow)
{
    Application::Run(gcnew CExercise());

    return 0;
}

Practical LearningPractical Learning: Introducing Forms

  1. Start Microsoft Visual C++ 2005 or Visual Studio 2005 and create a new Windows Forms Application named CPAR1
  2. Press Ctrl + F5 to test the program
  3. Close the form and return to your programming environment

The Form's Title Bar

 

The System Icon

A form is made of various sections that allow its control as a Windows object and other aspects that play a valuable part as a host of other objects. The top section of a form is made of a long portion called the title bar.

On the left side of the title bar, the form displays a small picture called an icon or the system icon. Microsoft Visual Studio 2005 provides a default icon for all forms. If you want to use a different icon, while the form is selected, in the Properties window, you can click the Icon field and then click its ellipsis button Ellipsis. This would launch the Open dialog box from where you can locate an icon and open it.

To change the icon programmatically, declare a variable of type Icon of the System::Drawing namespace and initialize it with the name of an icon file using the gcnew operator. After initializing the icon, assign it to the form's Icon property. Here is an example:

#include <windows.h>

#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;

public ref class CExercise : public Form
{
public:
    CExercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
	System::Drawing::Icon ^ customIcon =
			gcnew System::Drawing::Icon(L"C:\\Programs\\RedBook.ico");
        Icon = customIcon;
    }
};

Practical LearningPractical Learning: Configuring a Form's Title Bar

  1. In the Resource View, right-click CPAR1 -> Add -> Resource...
     
    Add Resource
  2. In the Add Resource dialog box, click Icon and click New
  3. Design the icon as follows:
     
    Icon Design
  4. To continue with the icon design, on the main menu, click Image -> New Image Type... On the New Icon Image Type, make sure the first 16x16, 16 colors item is selected:
     
    New Icon Image Type
  5. Click OK
  6. Design it as follows:
     
    Icon Design
  7. In the Resource View, click IDI_ICON1
  8. In the Properties window, change the filename to cpas.ico
  9. Change the ID to IDI_CPAS
  10. To save the icon, on the Standard toolbar, click the Save All button Save All
  11. Close the window tab that contains the icon designed
  12. Click the body of the form to make sure it is selected. In the Properties window, click Icon and click its ellipsis button Ellipsis
  13. On the Open dialog box, locate the folder in which you had saved the project and select the icon1 icon
     
  14. Click Open
     
    A form with a System icon
  15. Execute the application to test it
  16. Close it and return to your programming environment

The Form's Caption

On the right side of the system icon, there is a word or a group of words called the caption. By default, the caption displays the name of the form. If you want to change the caption, while the form is selected, in the Properties window, click the Text field and type anything you want. After typing the text, press Enter to display it on the form.

At design time, the caption is made of text that you type "as is". At run time, you can change the caption to display a more complex text that could be a changing time, the result of a calculation, etc. Here is an example:

public ref class CExercise : public Form
{
public:
    CExercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
	Text = L"Windows Fundmentals - Programming";
        Icon = gcnew System::Drawing::Icon(L"C:\\Programs\\RedBook.ico");
    }
};

This would produce:

Practical LearningPractical Learning: Setting a Form's Caption

  1. While the form is selected, in the Properties window, click Text and type
    College Park Auto Shop - Customer Repair Order
  2. Press Enter

The System Buttons

On the right side of the caption, there are three small buttons called the system buttons, made of the Minimize (Minimize,, or ), the Maximize (Maximize,, or ), and the Close (Close, , or ) buttons. The presence or absence of these buttons is controlled by the Boolean ControlBox property whose default value is True to indicate that the form will be equipped with the system buttons. If you set it to False, no system button would be displayed:

A form without the control box

In this case, the user would not be able to close the form using the system buttons. Therefore, if you create this type of form, make sure you provide the user with a way to close it.

The Minimize (Minimize,, or ) button is controlled by a Boolean property called MinimizeBox. By default, when you freshly create a form, this property is set to True and the form would display a Minimize button.

The Maximize (Maximize,, or ) button is controlled by the Boolean MaximizeBox property, which also is set to True by default. Depending on what you are trying to achieve in your application, you can change the value of either one or both of these properties. The four combinations are as follows:

MaximizeBox MinimizeBox Display Result
True True Minimum and Maximum Buttons The form can be minimized or maximized
True False Minimum and Maximum Buttons The form can be maximized but cannot be minimized
False True Minimum and Maximum Buttons The form can be minimized but cannot be maximized 
False False Minimum and Maximum Buttons The form can be neither minimized nor maximized

To change a system button programmatically, call the desired button's property and assign it a true or false value. Here is an example that makes sure the user cannot maximize the form:

public ref class CExercise : public Form
{
public:
    CExercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
	Text = L"Windows Fundmentals - Programming";
        Icon = gcnew System::Drawing::Icon(L"C:\\Programs\\RedBook.ico");
	
	ControlBox = true;
	MinimizeBox = true;
	MaximizeBox = false;
    }
};

This would produce:

Practical LearningPractical Learning: Configuring a Form's System Buttons

  1. To make sure that the user cannot maximize the form, on the Properties window, click the MaximizeBox field to reveal its combo box and select False
  2. Test the program
     
  3. Close the form and return to your programming environment

The Form's Position

 

The Form's Location

When you create an application and while you are designing the form, it is fixed in the top-left corner of the Form Designer. This is not the position the form would have when it runs. In fact, by default, a random position is set for the form when it comes up. Fortunately, you can specify where the form would be located when it comes up and you have various alternatives.

Like every control on an application, a form has a parent: the desktop. The desktop is the wide area of the monitor easily seen when the computer comes up. Everything on the computer is located with regards to this main parent. In the same way, a form uses the desktop to determine its "physical" location. Based on this, when an application is launched, its form occupies an area of the desktop. To locate its children, the desktop uses a Cartesian coordinate system whose origin is located on the top-left corner of the screen:

The Origin of the Windows default coordinate system

The horizontal measurements move from the origin to the right. The vertical measurements move from the origin to the bottom:

Axes of the Windows Coordinate System

The distance from the the desktop's left border to the form's left border is represented by the form's Left property. The distance from the desktop's top border to the form's top border is specified by the Top property. Therefore, the Left and the Top values are known as the form's location. This can be illustrated as follows:

The Form Location

To specify the default location of a form when the application is opened, in the Properties window, click the + button of the Location field to reveal the values of the location. If a value of a property is set to 0, the compiler would select a random value for it when the form comes up. Otherwise, you can change each value to a valid natural number.

If you want to programmatically set the location of the form, you can assign a value to its Left and/or its Top properties. Here is an example:

public ref class CExercise : public Form
{
public:
    CExercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
	Left = 228;
	Top  = 146;
    }
};

Alternatively, you can assign a Point variable to the form's Location property. Here is an example:

#include <windows.h>

#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;

public ref class CExercise : public Form
{
public:
    CExercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
	Location = Point(228, 146);
    }
};

The Startup Position of a Form

At design time, the X and Y values of the Location property allow you to specify a precise position for the form. At run time, the Left and Top properties accomplish the same purpose. The Form class provides an alternative position to specify the location of the form relative to its parent. This is the role of the StartPosition property, which is a value of the FormStartPosition enumerator. It provides the following five values:

Value Result
CenterParent The form will be positioned in the center of its parent. If the application is made of only one form, this form would be positioned in the middle of the desktop
CenterScreen The form will be positioned in the middle of the desktop even if this form is part of an application that is made of various forms.
Manual The form will use the values of the X, Y, Left, and/or Top properties of the Location
WindowsDefaultLocation The operating system will specify the form's position using a value known in Win32 as CW_USEDEFAULT

Based on this, to set the default relative location of a form when it comes up, change the value of its StartPosition combo box in the Properties window. To specify this characteristic when programmatically creating a form or to change this property at run time, call the FormStartPosition enumeration to select the desired value and assign it to the StartPosition property of the form. Here is an example:

public ref class CExercise : public Form
{
public:
    CExercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
	StartPosition = FormStartPosition::WindowsDefaultLocation;
    }
};

The StartPosition property provides another value that is related to the size. Therefore, we will mention it when we review the size of a form.

Practical LearningPractical Learning: Setting a Form's Default Position

  1. Click the middle of the form to make sure it is selected
  2. In the Properties window, click StartPosition to reveal its combo box. Click the arrow of its combo box and select CenterScreen
  3. Execute the application to view the result. Notice that it is centered on the screen
  4. Close it and return to your programming environment

The Window State of a Form

When creating your application, you can configure its (main) form to be minimized or maximized when the application is launched. This feature is controlled by the WindowState property. The default value of this property is Normal which means the form would appear in the same dimensions it was designed. If you want the form to be minimized or maximized at startup, in the Properties window, change the desired value of the WindowState property to Maximized or Minimized.

To control the window's state programmatically, assign the Maximized or Minimized value, which are members of the FormWindowState enumerator, to the WindowState property. Here is an example:

public ref class CExercise : public Form
{
public:
    CExercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
        Text = L"A Day at the Beach";
        Icon = gcnew System::Drawing::Icon(L"C:\\Programs\\RedBook.ico");
		
	WindowState = FormWindowState::Maximized;
    }
};

If you want to check the state of a window before taking action, simply use a conditional statement to compare its WindowState property with the Normal, the Maximized, or the Minimized values.

The Form's Taskbar Presence

When an application displays on the screen along with other applications, its form can be positioned on top of, or behind, forms of other applications. This is allowed by multitasking assignments. When a form is hidden, the taskbar allows you to access it because the form would be represented by a button. This aspect of forms is controlled by the ShowInTaskbar Boolean property. Its default value is True, which indicates that the form would be represented on the taskbar by a button.

If you create an application made of various forms, you may not want to show all of its forms on the taskbar. Usually the first or main form would be enough. To prevent a button for a form to display on the taskbar, set its ShowInTaskbar property to False.

Here is an example:

public ref class CExercise : public Form
{
public:
    CExercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
        Text = L"A Day at the Beach";
        Icon = gcnew System::Drawing::Icon(L"C:\\Programs\\RedBook.ico");
	WindowState = FormWindowState::Maximized;

        ShowInTaskbar = false;
    }
};
Author Note Unless you have a good reason, and it is hard to see what that reason could be, you should not set the ShowInTaksbar property of the first or main form of an application to false.
  
 
 
 

The Form's Measures

 

The Form's Size

A form's size is the amount of space it is occupying on the screen. It is expressed as its width and its height. The width of a form is the distance from its left to its right borders. The height is the distance from the top to the bottom borders of a form:

When you create a form, it assumes a default size. To set or change the size of a form, at design time, first click it to select it. Then, position the mouse on its right, bottom, or bottom-right handles. This changes the mouse cursor in one of three shapes:

Resizing a form

With the mouse positioned, drag in the desired direction.

If you don't want to be able to resize a form and you want to prevent this by accident, at design time, set the form's Locked property to True. If you do this:

  • A small picture of a lock displays in the top-left corner of the form:
  • The form gets surrounded by a rectangle with a black border
  • The sizing handles of the form disappear
The Locked property of the form set to True
Author Note Because Locked is only a design characteristic, it is not an actual property of the Form class. Therefore, you cannot use it to lock a form at run time. In order words, you cannot use the Lock feature to prevent the user from resizing a form.

Besides resizing the form by dragging one of its handles, to change the size of a form, select it and, in the Properties window, click the + button of the Size field. Then type the desired value for the Width and the desired value for the Height. The values must be natural numbers.

To programmatically change the size of a form, assign the desired values to either or both its Width and Height properties. Here is an example:

public ref class CExercise : public Form
{
public:
    CExercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
	Text = L"Windows Fundmentals - Programming";
        Icon = gcnew System::Drawing::Icon(L"C:\\Programs\\RedBook.ico");
	
	ControlBox = true;
	MinimizeBox = true;
	MaximizeBox = false;

	Width  = 425;
	Height = 308;
    }
};

Alternatively, you can assign a Size value to the Size property of the form. Here is an example:

public ref class CExercise : public Form
{
public:
    CExercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
	Text = L"Windows Fundmentals - Programming";
        Icon = gcnew System::Drawing::Icon(L"C:\\Programs\\RedBook.ico");
	StartPosition = FormStartPosition::WindowsDefaultLocation;

        ControlBox = true;
        MinimizeBox = true;
        MaximizeBox = false;

	Size = System::Drawing::Size(425, 308);
    }
};

If you want the operating system to specify the size of the form, set its StartPosition property to WindowsDefaultBounds. In this case, a value called CW_USEDEFAULT would be assigned to both the Width and the Height properties.

Practical LearningPractical Learning: Setting the Form's Default Size

  1. Position the mouse to the small square on the right border of the form
  2. Click and drag in the right direction to make sure the caption in the title bar can appear completely
     
    Resizing a form
  3. Release the mouse

The Form Borders

A form can be made to look like a regular rectangular host made of a system icon and the system buttons. Depending on your goals, you can also make a form appear as a dialog box or a dockable window. The borders of a form are controlled by the FormBorderStyle property.

If you set both the MinimizeBox and the MaximizeBox properties to False, we saw that the form would have only the system Close button, but the form can still be resized. If you want the form to display only the system Close button and to prevent the user from resizing it, set its FormBorderStyle property to FixedDialog. Here is an example:

public ref class CExercise : public Form
{
public:
    CExercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
	Text = L"Windows Fundmentals - Programming";
        Icon = gcnew System::Drawing::Icon(L"C:\\Programs\\RedBook.ico");
	StartPosition = FormStartPosition::WindowsDefaultLocation;

        ControlBox = true;
        MinimizeBox = true;
        MaximizeBox = false;

	Size = System::Drawing::Size(425, 308);

	FormBorderStyle = System::Windows::Forms::FormBorderStyle::Fixed3D;
    }
};

This would produce:

 

A tool window is a form equipped with a short title bar, no icon, and only a small system Close button. There are two types of tool windows.

  • A tool window is referred to as fixed if the user cannot resize it. In this case, the FormBorderStyle property of the form is set to FixedToolWindow:
     
    FormBorderStyle = FormBorderStyle::FixedToolWindow;
  • A tool window is referred to as sizable if it allows the user to resize it. To get such a form, set its FormBorderStyle property to SizableToolWindow:
     
    FormBorderStyle = FormBorderStyle::SizableToolWindow;

You can also create a form with no borders by assigning None to the FormBorderStyle property. If you do this, make sure you provide the user with a way to close the form; otherwise...

A Tool Window
 

The Client Area of a Form

 

Introduction

When a form has been created, you can add Windows controls to it. These controls can be positioned only in a specific area, the body of the form. The body spans from the left border of the form, excluding the border itself, to the right border of the form, excluding the border. It also spans from the top side, just under the title bar, to the bottom border, excluding the bottom border, of the form. The area that the form makes available to the controls added to it is called the client area:

Client Area

If a control is positioned on a form, its location uses a coordinate system whose origin is positioned on the top-left section of the client area (just under the title bar). The x axis moves from the origin to the left. The y axes moves from the origin down:

The origin of the coordinate system and its axes

The distance from the left border of the client area to the left border of the control is the Left property. The distance from the top border of the client area to the top border of the control is the Top property. These can be illustrated as follows:

The location of a control inside a parent window

 

To know the amount of space that a form is making available to its child control, you can access the form's ClientSize property.

The Background Color of a Form

The client area of a form is painted with a color specified by the operating system. To change the color to anything you like, you can use the BackColor field of the Properties window. If you click the arrow of its combo box, it displays a property sheet with three tabs that divide the color in categories:

Back Color Back Color Back Color

To programmatically change its color, assign a color from the Color structure to the BackColor property. Here is an example:

public ref class CExercise : public Form
{
public:
    CExercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
	BackColor = Color::BurlyWood;
    }
};

This would produce:

Back Color

The Background Image of a Form

If you prefer to cover the client area with a picture, use the BackgroundImage property instead. If using the Properties window, you can easily locate and select a picture.

To programmatically specify or change the picture used as background, declare and initialize a pointer to the Bitmap class. Then assign it to the BackgroundImage property. Here is an example:

public ref class CExercise : public Form
{
public:
    CExercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
        Text = L"A Day at the Beach";
        Icon = gcnew System::Drawing::Icon(L"C:\\Programs\\RedBook.ico");
		StartPosition = FormStartPosition::CenterScreen;

	BackgroundImage = Image::FromFile(L"E:\\Programs\\beach.jpg");
    }
};

Form Background

aaa 

Background Image Options

There are two ways you can use a background image on a form. You can fill the whole client area with the picture if the picture is bigger than the client area. If the picture is narrower and/or shorter than the picture, you can resize or repeat it. To assist you with making this decision, the Form class is equipped with a property named BackgroundImageLayout.

The Form.BackgroundImageLayout property is based on the ImageLayout enumeration. Its values are:

  • None: The picture will display once, from the top-left origin of the client area. Here is an example:
     
    BackgroundImage = Image::FromFile("C:\\Exercises\\FireWall.png");
    BackgroundImageLayout = ImageLayout::None;
  • Tile: The picture will start displaying from the top-left origin of the client area. Then it will repeat itself horizontally, followed by the next line, then the next, and so on. Here is an example:
     
    BackgroundImage = Image::FromFile("C:\\Exercises\\FireWall.png");
    BackgroundImageLayout = ImageLayout::Tile;
    BackgroundImageLayout = ImageLayout.Tile
  • Center: The picture will display once, in the middle-center of the client area of the form. Here is an example:
     
    BackgroundImage = Image::FromFile("C:\\Exercises\\FireWall.png");
    BackgroundImageLayout = ImageLayout::Center;
    BackgroundImageLayout = ImageLayout.Center;
  • Stretch: The picture will first be positioned in the middle of the client area of the form, then it will stretch itself to occupy the whole client area, and so on. Here is an example:
     
    BackgroundImage = Image::FromFile("C:\\Exercises\\FireWall.png");
    BackgroundImageLayout = ImageLayout::Stretch;
  • Zoom: The compiler will find out which measure is smaller between the width and the height of the client area of the form. That smaller measure will be used for both the width and the height of the picture. Here is an example:
     
    BackgroundImage = Image::FromFile("C:\\Exercises\\FireWall.png");
    BackgroundImageLayout = ImageLayout::Zoom;

    If the form's width is lower than its height, then the picture will be positioned in the middle of the form:

    If the form's height is lower than its width, then the picture will be positioned in the center of the form:

 

Methods and Events to Manage a Form

 

Form Creation

The form is implemented by the Form class from the System::Windows::Forms namespace. The Form class is equipped with a constructor that allows you to dynamically create it. After a form has been created, it must be loaded to display on the screen. When a form is being loaded, it fires the Load() event which is of type EventArgs. This event is fired when a form is about to be displayed for the first time. Therefore, it can be used to perform last minute initializations.

Form Activation

When two or more forms are running on the computer, only one can receive input from the user. This means that only one form can actually be directly used at one particular time. Such a window has a title bar with the color identified in Control Panel as Active Window. The other window(s), if any, display(s) its/their title bar with a color called Inactive Window.

To manage this setting, the windows are organized in a 3-dimensional coordinate system and they are incrementally positioned on the Z coordinate, which defines the (0, 0, 0) origin on the screen (on the top-left corner of the monitor) with Z coordinate coming from the screen towards you.

In order to use a form other than the one that is active, you must activate it. To do this, you can call the Activate() method. Its syntax is:

public:
    void Activate();

When a form is activated, it fires the Activated event, which is an EventArgs type of event.

Form Deactivation

If there is more than one form or application on the screen, only one can be in front of the others and be able to receive input from the others. If a form is not active and you want to bring it to the top, you must activate it, which fires the Activated() event. When a form is being activated, the one that was on top would become deactivated. The form that was on top, as it looses focus, would fire the Deactivate() event which is an EventArgs type.

Form Closure

When the user has finished using a form, he or she must be able to close it. Closing a form is made possible by a simple call to the Close() method. Its syntax is:

public:
     void Close();

When this method is called, the process of closing a form starts. At this time, the Closing() event is fired. The Closing() event is implemented by the CancelEventArgs class through the CancelEventHandler delegate. The CancelEventArgs class is equipped with only the Cancel property. The CancelEventArgs::Cancel property allows you to cancel or to continue with the closing of the form. If you set the CancelEventArgs::Cancel property to true, the event will be ignored as if it were not fired. If you want the event to continue closing the form, you can set this property to false. This event occurs before the form is actually closed, giving you time to let the form be closed, prevent the form from being closed, or take any other necessary action.

After a form has been closed, a Closed() event is fired. Although this method can be used to close any form of an application, if it is called by the main form, it also closes the application.

 
 
   
 

Previous Copyright © 2010-2016, FunctionX Next