Fundamentals of a Form

Introduction

An application is a list of instruction a perfon gives to a computer asking it to perform some action(s). On a regular graphical application, the most fundamental object through which the instructions are given is called a form.

Creating a Form

If you create a Windows Forms App (.NET Framework) or a Windows Forms App (.NET Core) project, the studio autocally generates a graphical application and equip it with a form. Alternatively, you can start an application from scratch at the command prompt or you can create an empty project in Microsoft Visual Studio:

Create a New Project

If you build your application at the command prompt or you start it from an empty application in Microsoft Visual Studio, in both cases, you must add a reference to the System.Windows.Forms.dll assembly.Here is an example:

Reference Manager

You should also add other references such as at least the System.dll and the System.Drawing.dll assemblies. Eventually, when writing your code, you will also need to add the System.Windows.Forms namespace to your code file. If you had created your application from an empty project, open the properties of the project and, in the Output Type combo box, select Windows Application:

The Properties of a Project

To programmatically create a form, you will use a class named Form. You have various options. You can declare a variable of type Form and use the new operator to initialize the variable, using the default constructor of the class. Here is an example:

using System.Windows.Forms;

public class Exercise
{
    public static void Main()
    {
        Form frmExercise = new Form();
    }
}

As another option, you can create a class derived from Form. Here is an example:

using System.Windows.Forms;

// Deriving a class from System.Windows.Forms.Form
public class Exercise : Form
{
}

Displaying a Form

After creating a form, to make the user use it, you must display it. You have various options but this depends on how you created the form and how you plan on displaying it. To let you simply display a form, the Form class is equipped with a method named Show (we will come back to this method). As another option, the Form class is equipped with a method named ShowDialog (we will also come back to it in a later section but we can use it currently). Here is an example:

using System.Windows.Forms;

public class Exercise
{
    public static void Main()
    {
        Form frmExercise = new Form();

        frmExercise.ShowDialog();
    }
}

Processing the Messages of an Application

An application is constantly generating messages through events. These events have to be processed. To help you process thos messages, the .NET Framework provides a sealed class named Application

public sealed class Application

Probably the first operation to perform on an application is to launch it. To support this operation, the Application class is equipped with an overloaded method named Run. One of the versions of this method allows you to specify the (main) form of the application. That version uses the following syntax:

public static void Run (System.Windows.Forms.Form mainForm);

You should call the Application.Run() method from the entry point of your application, which is the Main() function. You can declare a variable of a class derived from Form and pass that variable to the Application.Run() method. Here is an example:

using System.Windows.Forms;

public class Exercise : Form
{
    public static void Main()
    {
        Exercise exo = new Exercise();

        Application.Run(exo);
    }
}

Remember that you need a variable only if you are planning to use the variable many times. Otherwise, you can pass the initialization of the class directly where it is needed. Here is an example:

using System.Windows.Forms;

public class Exercise : Form
{
    public static void Main()
    {
        Application.Run(new Exercise());
    }
}

To better manage your code, you can separate the class of the form and the other classes. Here is an example:

using System.Windows.Forms;

public class Exercise : Form
{
}

public class Program
{
    public static void Main()
    {
        Application.Run(new Exercise());
    }
}

Initializing a Form

By .NET Framework standards, to initialize a variable, it is suggested that, if you derive a class from Form, you should create a method named InitializeComponent in that class, then call that method in a default constructor of your class. Here is an example:

public class Exercise : Form
{
    private void InitializeComponent()
    {
    }
    
    public Exercise()
    {
        InitializeComponent();
    }
}

public class Program
{
    static int Main()
    {
        Application.Run(new Exercise());
        return 0;
    }
}

The Form's Title Bar

The System Icon

A form is made of various sections that allow it to better manage the controls positioned on it. 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 provides a default icon for all forms. If you want to use a different icon, while the form is selected, in the Properties window, 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 new operator. After initializing the icon, assign it to the form's Icon property. Here is an example:

private void InitializeComponent()
{
    System.Drawing.Icon customIcon =
			new System.Drawing.Icon(@"C:\Programs\RedBook.ico");
    Icon = customIcon;
}

Whether you had assigned an icon to the form or not, you can control if the form should display an icon. To support this, the Form class is equipped with a Boolean property named ShowIcon. If you set this property to false, the icon would not appear in the title bar of the form. If the Form.ShowIcon property is set to true, which is its default value, the form's title bar would display an icon.

The Form's Caption

On the right side of the system icon, there is the title, also called the caption, of the form. By default, if you create a Windows Forms application using Microsoft Visual Studio, it sets the name of the form as its caption. 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.

At design time, the caption is made of text 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.

The System Buttons

On the right side of the caption, there are three small buttons called the system buttons, made of the Minimize (Minimize), the Maximize (Maximize), and the Close (Close) 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 Button

The Minimize button (Minimize) 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 Button

The Maximize button (Maximize) 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 Maximize = True and Minimize = True The form can be minimized or maximized
True False Maximize = True and Minimize = False The form can be maximized but cannot be minimized
False True Maximize = False and Minimize = True The form can be minimized but cannot be maximized 
False False Maximize = False and Minimize = False 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:

private void InitializeComponent()
{
    Icon = new System.Drawing.Icon(@"C:\Programs\RedBook.ico");
    Text = "Windows Fundmentals - Programming";

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

This would produce:

Control Box

The Form's Position

The Startup Position of a Form

When an application launches, you can control how and where you want the main form to appear. To assist you with this, the Form class is equipped wiih a property named StartPosition. This property is based on an enumeration named FormStartPosition. You cam specify this starting position of a form visually or programmatically. To set it visually, you can access the Properties window of the form and get to the StartPosition field. The members of the FormStartPosition enumeration are:

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:

using System;
using System.Windows.Forms;

public class Exercise : Form
{
    public Exercise()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        Icon = new System.Drawing.Icon(@"C:\Programs\RedBook.ico");
        Text = "Windows Fundmentals - Programming";

        StartPosition = FormStartPosition.WindowsDefaultLocation;
    }
}

The StartPosition property provides another value that is related to the size.

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. To let you set this feature, the Form class is equipped with a property named WindowState. This property is based on an enumeration namd FormWindowState. 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 other members of the FormWindowState enumeration, to the WindowState property. Here is an example:

using System;
using System.Drawing;

public class Exercise : System.Windows.Forms.Form
{
    public Exercise()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        Icon = new Icon(@"C:\Programs\RedBook.ico");
        Text = "Windows Fundmentals - Programming";

        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 a Boolean property named ShowInTaskbar. Its default value is True, which indicates that the form would be represented on the taskbar by a button. Here is an example:

private void InitializeComponent()
{
        Icon = new Icon(@"C:\Programs\RedBook.ico");
        Text = "Windows Fundmentals - Programming";

        ShowInTaskbar = false;
}
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. As seen in previous lessons, the size of a form can be expressed as its width and its height. This can be illustrated as follows:

The Size of a Form

When you create a form, it assumes a default size (300 x 300). 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:

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 other 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, as seen in previous lessons, assign the desired values to either or both its Width and Height properties. Here is an example:

private void InitializeComponent()
{
    Icon = new Icon(@"C:\Programs\RedBook.ico");
    Text = "Windows Fundmentals - Programming";

    Width = 425;
    Height = 308;
}

Alternatively, to let you specify the size of a form, the Form class is equipped with a property named ClientSize that is of type Size. Here is an example of using it to specify the size of a form:

private void InitializeComponent()
{
    Icon = new Icon(@"C:\Programs\RedBook.ico");
    Text = "Windows Fundmentals - Programming";

    ClientSize = new 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.

The Form Borders

A form can be made to appear with a system icon and the system buttons. Depending on your goals, you can also make a form appear as a dockable window. The borders of a form are controlled by a property named FormBorderStyle.

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:

private void InitializeComponent()
{
    Icon = new Icon(@"C:\Programs\RedBook.ico");
    Text = "Windows Fundmentals - Programming";

    FormBorderStyle = 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 area that the form makes available to the controls added to it is called the client area:

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

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:

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 class Exercise : System.Windows.Forms.Form
{
    public Exercise()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        Icon = new Icon(@"C:\Programs\RedBook.ico");
        Text = "Windows Fundmentals";

        BackColor = Color.BurlyWood;
    }
}

The Background Image of a Form

Introduction

If you prefer to cover the client area of a form with a picture, use the BackgroundImage property. Here is an example:

private void InitializeComponent()
{
    Icon = new Icon(@"C:\Programs\RedBook.ico");
    Text = "A Day at the Beach";
    MaximizeBox = false;

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

Form Background

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 an enumeration named ImageLayout. Its values are:

Methods and Events to Manage a Form

Form Creation

After a form has been created, it must be loaded to display on the screen. When a form is being loaded, it fires an event named Load. It 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 some last minute initializations. As the default event of a form, to set it up at design time, you can double-click the body of the form.

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 let you do this, the Form class is equipped with a method named Activate. Its syntax is:

public void Activate();

When a form is activated, it fires an event named Activated. It is of type EventArgs.

Form Deactivation

If there is more than one form or application on the screen, only one form 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. This can be done by clicking its title bar or its button on the taskbar. This action causes the form to fire an event named Activated. 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 an event named Deactivate. It is of type EventArgs.

Starting to Close a Form

To let you close a form, the Form class is equipped with a method named Close. Its syntax is:

public void Close();

To close a form, call this method on a variable of a form.

Closing a Form

When the Form.Close() method is called, the process of closing a form starts. At this time, the form fires an event named Closing. The Closing event is implemented by the CancelEventArgs class through the CancelEventHandler delegate. The CancelEventArgs class is equipped with only a property named Cancel. 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, 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 perform any other necessary action.

Having Closed a Form

After a form has been closed, it fires an event named Closed. Although this event can be used to close any form of an application, if it is implemented by the main form, it also closes the application.

Introduction to Dialog Boxes

Description

A dialog box is a form defined with particular properties. Here is an example of a dialog box:

The Run dialog box

A dialog box has the following characteristics:

Creating a Dialog Box

To create a dialog box, start with a form, which you can get by creating a Windows Forms application or deriving a class from Form. Here is an example:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Exercise : Form
{
    public Exercise()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        Text = "Domain Configuration";
        Width = 320;
        Height = 150;
        Location = new Point(140, 100);
        StartPosition = FormStartPosition.CenterScreen;
    }
}

public class Program
{
    static int Main()
    {
        Application.Run(new Exercise());
        return 0;
    }
}

This would produce:

Starting a dialog box

Characteristics of Dialog Boxes

The Border Style of a Dialog Box

There are a few actions you should perform on a form to transform it into a dialog box; but normally, these are only suggestions, not rules. Based on the Microsoft Windows design and standards, to create a dialog box, you should set a form's FormBorderStyle property to FixedDialog. Setting this property changes the borders of the form to the standard borders of a dialog box (the border of a dialog box is thinner than that of a regular form). You can set this characteristic in the Properties window or programmatically. Here is an example:

private void InitializeComponent()
{
    Text = "Domain Configuration";
    Width = 320;
    Height = 150;
    Location = new Point(140, 100);
    StartPosition = FormStartPosition.CenterScreen;

    FormBorderStyle = FormBorderStyle.FixedDialog;
}

The Minimize and Maximize Boxes

Besides taking care of the border, you should also set both the MinimizeBox and the MaximizeBox properties to False. This causes the window to display only the system Close button. You can set these characteristics in the Properties window or programmatically. Here is an example:

private void InitializeComponent()
{
    Text = "Domain Configuration";
    Width = 320;
    Height = 150;
    Location = new Point(140, 100);
    StartPosition = FormStartPosition.CenterScreen;

    FormBorderStyle = FormBorderStyle.FixedDialog;
    MinimizeBox = false;
    MaximizeBox = false;
}

This would produce:

Form

Closing a Dialog Box

You should provide a way for the user to close the dialog box. A dialog box should have at least one button labeled OK. This button allows the user to acknowledge the message of the dialog box and close it by clicking the button. If the user press Enter, the dialog box should also be closed as if the OK button was clicked.

Accepting an Action

Most of the time, if you are creating a dialog box, you should add a button to it and set the caption of that button as OK. The OK button should be the default so that if the user presses Enter, the dialog box would be closed as if the user had clicked OK. Clicking OK or pressing Enter would indicate that, if the user had made changes on the controls of the dialog box, those changes would be acknowledged and kept when the dialog box is closed and usually the changed values of the control would be transferred to another dialog box or form. Keep in mind that you are responsible for implementing this functionality.

To fulfill this functionality of the OK button, after adding it to a dialog box, the Form class is equipped with a property named AcceptButton. To visually manage it, access the AcceptButton combo box in the Properties window for the form and select the name of the button.

Cancelling an Action

Most of the time, if you are creating a dialog box, besides the OK button, it should also have a Cancel button. The Cancel button is used to allow the user to dismiss whatever changes would have been made on the controls of the dialog box. The dialog box should also be configured so that if the user presses Esc, the dialog box would be closed as if the user had clicked Cancel.

To fulfill this functionality of the Cancel button, after adding it to a dialog box (or form), the Form class is equipped with a property named CancelButton. To visually set it, access its combo box in the Properties window for the form and select the name of the button.

Besides the OK and the Cancel buttons, a dialog box can be created with additional buttons such as Finish or Help, etc. It depends on its role and the decision is made by the application developer.

The Help Button

Besides the system Close button, if you are planning to provide help on a dialog box, you can equip it with a Help button. To support this, the Form class is equipped with a Boolean property named HelpButton. The default value of this property is false. In the Properties window, you can set it to True. If you are programmatically creating the dialog box, you can access this property and set its value to true. Here is an example:

private void InitializeComponent()
{
    Text = "Domain Configuration";
    Width = 320;
    Height = 150;
    Location = new Point(140, 100);
    StartPosition = FormStartPosition.CenterScreen;

    FormBorderStyle = FormBorderStyle.FixedDialog;
    MinimizeBox = false;
    MaximizeBox = false;

    HelpButton = true;
}

This would produce:

Form

When the user clicks the help button, the mouse cursor becomes equipped with a question mark. Here is an example:

Form

You can then write code so that, when the user clicks a control on the dialog box, some guiding help is provided as a tool tip.

Modal and Modeless Dialog Boxes

Modal Dialog Boxes

There are two types of dialog boxes: modal and modeless.

A modal dialog box is one that the user must first close in order to have access to any other form or dialog box of the same application. One of the scenarios in which you use a dialog box is to create an application that is centered around one. In this case, if either there is no other form or dialog box in your application or all the other forms or dialog boxes depend on this central dialog box, it must be created as modal. Such an application is referred to as dialog-based.

Some applications require various dialog boxes. In this case, you may need to call one dialog box from another and display it as modal.

After creating a dialog box used as an addition to an existing form or an existing dialog box, to let you call it as modal, the Form class is equipped with a method named ShowDialog.

Modeless Dialog Boxes

A dialog box is referred to as modeless if the user does not have to close it in order to continue using the application that owns the dialog box. A modeless dialog box has the following characteristics

Since the modeless dialog box does not display its button on the task bar, the user should know that the dialog box is opened. To make the presence of a modeless dialog box obvious to the user, it typically displays on top of its host application until the user closes it.

A modeless dialog box is created from a form but it should look like a regular dialog box or a tool window. Therefore, to create a modeless dialog box, set the FormBorderStyle property to an appropriate value such as FixedSingle, FixedToolWindow, Sizable or SizableToolWindow. Also, set its ShowInTaskbar property to False.

After creating the dialog box, to let youdisplay it as modeless, the Form class is equipped with a method named Show. The fundamental difference between the ShowDialog() and the Show() methods is that the former displays a modal dialog box, which makes sure that the called dialog box cannot go in the background of the main application. By contrast, the Show method only calls the dialog box every time it is requested. For this reason, it is up to you to make sure that the modeless dialog box always remains on top of the application. This is easily taken care of by setting the Boolean TopMost property of the form to True.

There are two main ways a normal modeless dialog box can be dismissed:


Previous Copyright © 2001-2021, C# Key Next