Home

Form and Dialog-Based Applications

 

A Multi-Form Application

 

Introduction

When you create a Windows Application, the starting form is made available to you. If one form is not enough for your application, you can add as many as necessary. To add (or to create) a (new) form, you have various options:

  • On the main menu, you can click Project -> Add Windows Form...

  • On the main menu, you can click Project -> Add New Item...

  • On the main menu, you can click File -> Add New Item...

  • In Solution Explorer, you can right-click the name of the project and click Add Windows Form...

  • In Solution Explorer, you can right-click the name of the project and click Add New Item...

In the Add New Item dialog box, if you had selected Add Windows form previously, type a name in the Name text box and press Enter. If you had selected Add New Item in the above steps, then in the Templates section, click Window Form (.NET), provide a name in the Name edit box and click Open.

If your application is using various forms and you want to display a particular one at design time:

  • In the Forms Designer, you can click the tab that corresponds to the desired form
  • On the main menu, you can click Window and click the name of the form in the list under Close All Documents
  • In Solution Explorer, double-click the name of the desired form

If you visually add two (or more) forms to your application, you may need to link them, allow one to call the other. To do this, declare a variable of the other form and use the new operator to allocate memory for it. To display the other form, you can call its Show() method.

Practical LearningPractical Learning: Using Various Forms

  1. Create a new Windows Application and name it MultiForms1
  2. While the new form is still displaying, in the Properties window, click Text and type
    Central Unit
  3. Click Size, type 520, 350 and press Enter
  4. To add another form, on the main menu, click Project -> Add Windows Form...
  5. In the Add New Item dialog box, replace the contents of the Name edit box with Second and press Enter
  6. While the second form is still displaying, in the Properties window, edit its Text property to display Second Step
  7. Set its ShowInTaskbar property to False
  8. To display the first form, in the Form Designer, click the Form1.cs [Design] tab
  9. In the Properties window, click the Events button Events
  10. Double-click the DoubleClick field
  11. Implement the event as follows:
     
    private void Form1_DoubleClick(object sender, System.EventArgs e)
    		{
    			Form Other = new Second();
    			Other.Show();
    		}
  12. Execute the application
  13. If you double-click the first form, the second would display. You may find out that there is a problem in the fact that every time you double-click the first form, a new instance of the second form displays, which may not be very professional
  14. Close it and return to Visual C#
  15. To display the second form, in the Forms Designer, click the Second.cs [Design] tab
  16. In the Properties window, click the Events button Events
  17. Double-click the Closing field, and implement it as follows:
     
    private void Second_Closing(object sender, 
    		System.ComponentModel.CancelEventArgs e)
    {
    	// When the user attempts to close the form, don't close it...
    	e.Cancel = true;
    	// only hide it
    	this.Visible = false;
    }
  18. To display the code file of the first form, in the Code Editor, click the Form1.cs tab
  19. Change its code as follows:
     
    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    
    namespace WindowsApplication6
    {
    	/// <summary>
    	/// Summary description for Form1.
    	/// </summary>
    	public class Form1 : System.Windows.Forms.Form
    	{
    		/// <summary>
    		/// Required designer variable.
    		/// </summary>
    		private System.ComponentModel.Container components = null;
    		private Form Other;
    
    		public Form1()
    		{
    			InitializeComponent();
    
    			Other = new Second();
    		}
    
    		. . . No Change
    
    		/// <summary>
    		/// The main entry point for the application.
    		/// </summary>
    		[STAThread]
    		static void Main() 
    		{
    			Application.Run(new Form1());
    		}
    
    		private void Form1_DoubleClick(object sender, System.EventArgs e)
    		{
    			Other.Visible = true;
    		}
    	}
    }
    
  20. Execute the application
  21. Close it and return to your programming environment
 
 

Inherited and Derived Forms

Besides adding a form by using the previously reviewed technique, you can create a form that is based on another existing form. This is done through inheritance. All of the forms we have used so far were in fact classes derived from the .NET Framework's Form class of the System.Windows.Forms namespace. If you create a good looking or good functional form, you can create another form that is simply based on that first form. This can simplify design and functionality because the new form can use all of the functionality of the base. You can then only build on top of it.

After creating a form, to derive another form from it, on the main menu, click Project -> Add Inherited Form... In the Add New Item dialog box, you can type a name for the new form and click Open. This will open the Inheritance Picker dialog box in which you can select an existing form. The Inheritance Picker dialog box displays, in a list view, the form that exist in the current application. If you have the base form in an external library, you can click the Browse button, locate the library that contains the base form and open it, then select the desired form. After selecting the base form, click OK

Practical LearningPractical Learning: Using an Inherited Form

  1. Create a Windows Application named Inherited
  2. To add another form, on the main menu, click Project -> Add Windows Form...
  3. Set the Name of the form to About and press Enter
  4. Click the middle of the form to select it
  5. In the Properties window, click Text and type About this Application...
  6. Click FormBorderStyle, then click its combo box and select FixedDialog
  7. Set both MaximumBox and MinimizeBox to False
  8. On the Toolbox, click Button and click the form
  9. While the new button is still selected, in the Properties, change its Text to Close and its Name to btnClose
  10. Double-click the Close button and implement its Click event as follows:
     
    private void btnClose_Click(object sender, System.EventArgs e)
    		{
    			Close();
    		}
  11. Display the first form and add a Button to it
  12. Change its Text to About and its Name to btnAbout
  13. Double-click the About button and implement its Click event as follows:
     
    private void btnAbout_Click(object sender, System.EventArgs e)
    		{
    			Form frmAbout = new About();
    
    			frmAbout.Show();
    		}
  14. Test the application and then close it
  15. To add an inherited form, on the main menu, click Project -> Add Inherited Form...
  16. Set the Name of the new form to Helper and click Open
  17. In the Inheritance Picker, click About
     
    Inheritance Picker
  18. Click OK
  19. Add a new Button to the new form
  20. Set its Text to Validate and its Name to btnValidate
  21. Double-click the new Validate button and implement its Click event as follows:
     
    private void btnValidate_Click(object sender, System.EventArgs e)
    {
    	MessageBox.Show("This is an acknowledgement from the inheritance");
    }
  22. Display the About form and add a CheckBox control to it
  23. Double-click the CheckBox control and implement its event as follows:
     
    private void checkBox1_CheckedChanged(object sender, System.EventArgs e)
    		{
    			if( this.checkBox1.Checked == true )
    				this.Text = "Checked";
    			if( this.checkBox1.Checked == false )
    				this.Text = "Non Checked";
    		}
  24. Display the first form and add a new button to it
  25. Set its Text to Helper and its Name to btnHelper
  26. Double-click the Helper button and implement its Click event as follows:
     
    private void btnHelper_Click(object sender, System.EventArgs e)
    		{
    			Helper frmHelp = new Helper();
    
    			frmHelp.ShowDialog();
    		}
  27. Test the application

Dialog Boxes

 

Introduction

A dialog box is a form defined with particular properties. Like a form, a dialog box is referred to as a container. It is the primary interface of user interaction with the computer. Like a form, a dialog box is mostly used to host child controls, insuring the role of dialog between the user and the machine. Here is an example of a dialog box:

The Create New Folder dialog box

A dialog box has the following characteristics:

  • It is equipped with the system Close button System Close . As the only system button, this button allows the user to dismiss the dialog and ignore whatever the user would have done on the dialog box
  • It cannot be minimized, maximized, or restored. A dialog box does not have any other system button but Close
  • It is usually modal, in which case the user is not allowed to continue any other operation on the same application until the dialog box is dismissed
  • It provides a way for the user to close or dismiss it
 

Dialog Box Creation

There are two main actions you can 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 assign it the standard borders of a dialog box (the border of a dialog box is thinner than that of a regular form)
  • You should set both the MinimizeBox and the MaximizeBox properties to False. This causes the window to display only the system Close button
  • 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.

Often the user will be presented with various options on a dialog box and may be asked to make a decision on the available controls. Most of the time, if you are creating such a dialog box, besides the OK button, it should also have a Cancel button. 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 (or form), open the AcceptButton combo box in the Properties window for the form and select the name of the 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), open the CancelButton 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.

 

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 framed window 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 to complete their functionality. When in case, you may need to call one dialog box from another and display it as modal. Here is an example:

The Date and Time dialog box of WordPad is modal: when it is displaying, the user cannot use any other part of WordPad unless he or she closes this object first Modal
 

After creating a dialog used as an addition to an existing form or an existing dialog box, to call it as modal, use the ShowDialog() method. 

 

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

  • It has a thin border
  • It can be neither minimized nor maximized. This means that it is not equipped with the Minimize or the Maximize buttons
  • It is not represented on the taskbar with a button
  • It must provide a way for the user to close it

Here is an example:

The Find (and the Replace) dialog box of WordPad (also the Find and the Replace dialog boxes of most applications) is an example of a modeless dialog box. If it is opened, the user does not have to close it in order to use the application or the document in the background. Modeless

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.

Just like the Modal dialog box, to create a modeless dialog box, once you have added a form to your application, to call it as a modeless dialog box, simply call the Show() method. The only thing you need to take care of is the fact that the dialog box can disappear behind the form that called 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.

The fundamental difference between the ShowDialog() and the Show() methods is that the first 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. The .NET Framework inherently supports message boxes through its own MessageBox class. Besides this, you can also use functions from either the Visual Basic or the Win32 libraries.

 

The MessageBox Class

The .NET Framework provides the MessageBox class function used to easily create a message box. To display a simple message with just an OK button, call the Show() static method of this class with the following syntax:

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:

private void button1_Click(object sender, System.EventArgs e)
{
	MessageBox.Show("Welcome to the Wonderful World of Visual C#");
}

This would produce:

Message Box

This 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.

In reality, the MessagBox.Show() method is overloaded with various versions. Another version is:

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:

private void button1_Click(object sender, System.EventArgs e)
{
	MessageBox.Show("Welcome to the Wonderful World of Visual C#",
                                               "Visual C# Tutorials");
}

This would produce:

Another version of the MessageBox.Show() method is as follows:

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 the MessageBoxButtons enumerator. Its members are:

MessageBoxButtons  Display
OK OK
OKCancel OK Cancel
YesNo Yes No  
YesNoCancel Yes No Cancel
RetryCancel Retry Cancel
AbortRetryIgnore Abort Retry Ignore

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

private void button1_Click(object sender, System.EventArgs e)
		{
			MessageBox.Show("Welcome to the Wonderful World of Visual C#",
				            "Visual C# Tutorials",
				            MessageBoxButtons.OKCancel);
		}

This would produce:

Message Box With Buttons

Besides displaying a message, the MessageBox.Show() method is meant to let you know what button the user clicked on a message box. As such, it can return a value. This value corresponds to the particular button the user clicks on the message box. The return values are defined in the DialogResult enumerator. Depending on the buttons the message box is displaying, after the user has clicked, the MsgBox() function can return one of the following values:

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 MessageBox.Show() method also comes in another version as follows:

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

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

Besides the buttons, you can display an icon on the message box. The available icons are:

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

Here is an example:

private void button1_Click(object sender, System.EventArgs e)
{
	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

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:

private void button1_Click(object sender, System.EventArgs e)
{
	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);
}
Message Box With an Icon

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:

private void button1_Click(object sender, System.EventArgs e)
{
	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);
}
Message Box With an Icon

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

private void button1_Click(object sender, System.EventArgs e)
{
	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);
}
Message Box With an Icon
 

The Win32 API's Message Box

Besides, or instead of, the .NET Framework's MessageBox class, you can use the Win32 API's MessageBox function to display a message box. Its syntax is:

int MessageBox(HWND hWnd,
    	          LPCTSTR lpText,
    	          LPCTSTR lpCaption,
    	          UINT uType);

This function provides the same options as the MessageBox.Show() method reviewed earlier. To use this function, you must include its library as we reviewed in previous lessons.

 

Previous Copyright © 2004-2010 FunctionX, Inc. Next