The Background Image of a Form

Introduction

The form is the primary object that serves the users of your application. One way you can make a form look appealing is by coverring it with a picture. To support this, the Control class is equipped with a property named BackgroundImage:

public virtual System.Drawing.Image BackgroundImage { get; set; }

The Form class inherits the BackgroundImage property from the Control class. As a result, you can use this property to visually or programmatically paint a form with a picture. 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

Practical LearningPractical Learning: Starting a Project

  1. Start Microsoft Visual Studio
  2. In the Visual Studio 2022 dialog box, click Create a New Project
  3. In the Create a New Project wizard page, in the list of projects templates, click Windows Forms App
  4. Click Next
  5. In the Configure Your New Project wizard page, change the Project Name to Exercise7
    Accept or change the project Location
  6. Click Next
  7. In the Framework combo box, select the highest version (.NET 8.0 (Long-Term Support)).
    Click Create
  8. To execute, on the main menu, click Debug -> Start Without Debugging:
  9. Close the form and return to your programming environment
Author Note

Author Note

If you want, using the form of the application you created, you can apply the descriptions in the following sections to experiment with, and get, the same results.

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:

public virtual System.Windows.Forms.ImageLayout BackgroundImageLayout { get; set; }

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:

public event EventHandler 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:

public event EventHandler Activated;

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.

public event EventHandler Deactivate;

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.Drawing;
using System.Windows.Forms;

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

    private void InitializeComponent()
    {
        Text = "Domain Configuration";
        Width = 450;
        Height = 250;
        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:

public System.Windows.Forms.IButtonControl AcceptButton { get; set; }

To visually manage this property, 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:

public System.Windows.Forms.IButtonControl CancelButton { get; set; }

To visually set this property, 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:

public System.Windows.Forms.DialogResult ShowDialog ();

To display a form, call this method applied to the Form variable. Here is an example:

using System.Windows.Forms;

public class Exercise
{
    Form frmExercise = new Form();

    private void Create()
    {
        frmExercise.ShowDialog();
    }

    public static void Main()
    {
        Exercise exo = new Exercise();
        exo.Create();
    }
}

You can also call this method from a variable that accesses the Form object. Here is an example:

using System.Windows.Forms;

public class Exercise
{
    public Form frmExercise = new Form();

    public static void Main()
    {
        Exercise exo = new Exercise();
        exo.frmExercise.ShowDialog();
    }
}

This makes it possible for the control to appear on the form when the form displays to the user.

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:

Message Boxes

Introduction

A message box is a special dialog box used to display a piece of information to the user. As opposed to a regular form, the user cannot type anything in the dialog box. To support message boxes, the .NET Framework provides a static class named MessageBox. Besides this, you can also use functions from either the Visual Basic language or the Win32 library.

If you want to use the Visual Basic language to display a message box, first add a reference of the Microsoft.VisualBasic.dll to your project (to the References node of the Solution Explorer). To support message boxes, the Visual Basic language provides a function named MsgBox that is a member of the Interaction class.

The Return Value of a Message Box

The primary purpose of a message box is to display a message. Besides displaying a message, a message box may let the user make a decision by clicking a button. Depending on the button the user would have clicked, the message box would return a value. The value returned by a message box corresponds to the particular button the user would have clicked (on the message box). The return values of a message box are defined in an enumeration named DialogResult. The buttons and the returned values are as follows:

If the User Clicks The method Returns
Abort DialogResult.Abort
Cancel DialogResult.Cancel
Ignore DialogResult.Ignore
No DialogResult.No
OK DialogResult.OK
Retry DialogResult.Retry
Yes DialogResult.Yes

The Interaction.MsgBox() function of the Visual Basic language returns a member of an enumeration named MsgBoxResult.

The Message of a Message Box

The .NET Framework provides the MessageBox static class to easily create a message box. To display a simple message with just an OK button, you can call its static Show() method. Its syntax is as follows:

public static DialogResult MessageBox.Show(string message);

In this case, the message to display must be passed as a string to the Show() method. Here is an example:

using System.Windows.Forms;

public class Exercise
{
    static int Main()
    {
        MessageBox.Show("Welcome to the Wonderful World of C# programming");
        return 0;
    }
}

This would produce:

Message Box

The message to display can be made of up to 1024 characters. To display the message on multiple lines, you can use the new line escape sequence anywhere inside the string.

Here is the Visual Basic version of the above code:

using Microsoft.VisualBasic;

public class Exercise
{
    static void Main()
    {
        Interaction.MsgBox("Welcome to the wonderful world of C# programming.");
    }
}

The Caption of a Message Box

The MessagBox.Show() method is overloaded with various versions. Another version uses the following syntax:

public static DialogResult Show(string text, string caption);

This version allows you to specify a custom caption for the message box. With this version, the first argument is the string that the user will see displaying on the message box. You can pass it as a string. You can also create it from other pieces of strings.

The second argument, caption, will be the sentence to display in the title bar of the message box. Here is an example:

using System.Windows.Forms;

public class Exercise
{
    static void Main()
    {
        MessageBox.Show("Welcome to the wonderful world of C# programming", "Exercise");
    }
}

This would produce:

The Visual Basic version of the above code is:

using Microsoft.VisualBasic;

public class Exercise
{
    static void Main()
    {
        Interaction.MsgBox("Welcome to the wonderful world of C# programming.", 0, "Exercise");
    }
}

The Buttons of a Message Box

Another version of the MessageBox.Show() method uses the following syntax:

public static DialogResult Show(string text, string caption, MessageBoxButtons buttons);

This version allows you to display one or more buttons on the message box. The available buttons are defined through an enumeration named MessageBoxButtons. In the Visual Basic language, the buttons of the message box are controlled by an enumeration named MsgBoxStyle. In the Visual Basic language, the buttons of the message box are controlled by an enumeration named MsgBoxStyle. The members of these enumerations are:

MessageBoxButtons MsgBoxStyle Message Box Buttons
OK OKOnly 0 OK
OKCancel OKCancel 1 OKCancel
YesNo YesNo 4 Yes
YesNoCancel YesNoCancel 3 Yes No Cancel
RetryCancel RetryCancel 5 Retry Cancel
AbortRetryIgnore AbortRetryIgnore 2 Abort Retry Ignore

To use any of these combinations of buttons, call the MessageBoxButtons enumeration and access the desired combination. Here is an example:

using System.Windows.Forms;

public class Exercise
{
    static int Main()
    {
        MessageBox.Show("Welcome to the wonderful world of C# programming",
                        "Exercise",
                        MessageBoxButtons.OKCancel);
        return 0;
    }
}

This would produce:

Message Box With Buttons

The Icon of a Message Box

This version allows you to display an icon. The possible icons are available through the MessageBoxIcon enumeration. The members of this enumerator are:

MessageBoxIcon Description
None    
Asterisk Asterisk Asterisk
Error Critical Error
Exclamation Exclamation Exclamation
Hand Critical Hand
Information Information Information
Question Question Question
Stop Critical Stop
Warning Exclamation Warning

Here is an example:

public class Exercise
{
    static void Main()
    {
        MessageBox.Show("Your order appears to be correct" +
                        "\nAre you ready to provide your credit card information?",
                        "Customer Order Processing",
                                              MessageBoxButtons.YesNoCancel,
                                              MessageBoxIcon.Information);
    }
}

This would produce:

Message Box With an Icon

The Default Button of a Message Box

When a message box is configured to display more than one button, the operating system is set to decide which button is the default. The default button has a thick border that sets it apart from the other button(s). If the user presses Enter, the message box would behave as if the user had clicked the default button. If the message box has more than one button, you can decide what button would be the default. To specify the default button, the MessageBox.Show() method provides the following version:

public static DialogResult Show(string text,
                                string caption,
                                MessageBoxButtons buttons,
                                MessageBoxIcon icon,
                                MessageBoxDefaultButton defaultButton);

Based on this, you can specify the default button using the last argument that provides values through the MessageBoxDefaultButton enumerator whose values are:

Button1: The left button will be the default. Here is an example:

public class Exercise
{
    static void Main()
    {
	    MessageBox.Show("Your order appears to be correct" +
                        "\nAre you ready to provide your credit card information?",
		                "Customer Order Processing",
                        MessageBoxButtons.YesNoCancel,
			            MessageBoxIcon.Information,
                        MessageBoxDefaultButton.Button1);
    }
}

This would produce:

Message Box With a Defauft Button

Button2: If the message box displays two buttons, the right button will be the default. If the message box displays three buttons, the middle button will be the default. Here is an example:

public class Exercise
{
    static void Main()
    {
       	MessageBox.Show("Your order appears to be correct" +
                        "\nAre you ready to provide your credit card information?",
	                    "Customer Order Processing",
                        MessageBoxButtons.YesNoCancel,
			            MessageBoxIcon.Information,
                        MessageBoxDefaultButton.Button2);
    }
}

This would produce:

Message Box With a Default Button

Button3: The right button will be the default. Here is an example:

public class Exercise
{
    static int Main()
    {
       	MessageBox.Show("Your order appears to be correct" +
                        "\nAre you ready to provide your credit card information?",
	                    "Customer Order Processing",
                        MessageBoxButtons.YesNoCancel,
			            MessageBoxIcon.Information,
                        MessageBoxDefaultButton.Button3);
    }
}

This would produce:

Message Box With a Default Button

ApplicationPractical Learning: Ending the Lesson


Previous Copyright © 2001-2024, FunctionX Friday 10 June 2022 Next