Home

Graphical Applications Fundamentals

 

Overview of GUI Applications

 

Introduction

Microsoft Visual C# is a programming environment that allows you to create various types of applications. In our lessons, we will create graphical applications, also called Windows applications or Windows Forms applications. 

A Windows application primarily appears as a rectangular object that occupies a portion of the screen. This type of object is under the management of the operating system: Microsoft Windows. Based on the functionality of Microsoft Windows, for an application to become useful, it must be opened. An application must have an entry point. On a C/C++ application, this entry point is a function called main.

On a Win32 application, this entry point is a function called WinMain. The C# language defines this entry point with a class's method named Main, as you should know already from your learning C# (some languages like Pascal or JScript .NET don't explicitly designate an entry point but they make it clear and the operating system knows where it is).

The Main() method of C# can be defined as void or as returning an integer value.

Practical LearningPractical Learning: Starting a GUI Application

  1. Start Microsoft Visual C#
  2. To create a new application, on the main menu, click File -> New Project or File -> New -> Project...
  3. In the Templates section, click Empty Project
  4. In the Name edit box, type Exercise2 and click OK
  5. On the main menu, click Project -> Add New Item...
  6. In the Templates list, click Code File
  7. Change the Name to Starter
     
    Add New Item
  8. Click Add
  9. Change the contents of the file as follows:
     
    using System;
    
    public class Starter
    {
        public static int Main()
        {
            return 0;
        }
    }

Windows Application Configuration

Although you can directly create a graphical application when starting your project, if you had created a console application, you can still easily transform it into a Forms application:

  • The most required action consists of changing some characteristics of the project. To take care of this, on the main menu, you can click Project -> ProjectName Properties... and then change the value of the Output Type combo box to Windows Application
  • Before or after setting the Output Type to Windows Application, you can create a form 

Practical LearningPractical Learning: Configuring a Windows Application

  1. On the main menu, click Project -> Exercise2 Properties...
  2. On the left side, make sure Application is selected.
    In the right section, click the arrow of the Output Type combo box and select Windows Application
     
    Properties
  3. Save and close the window

Forms Fundamentals

Windows Forms is a technique of creating computer applications based on the common language runtime (CLR). It offers a series of objects called Windows Controls or simply, controls. These controls are already created in the .NET Framework through various classes. Application programming consists of taking advantage of these controls and customizing them for a particular application. To exploit these controls and other features of the .NET Framework, there are various types of applications you can create, including graphical applications (Windows Application), web-based applications (ASP.NET Web Application), console applications (Console Application), etc.

The objects used in a Windows application are stored in libraries also called assemblies. As normal libraries, these assemblies have the extension .dll (which stands for dynamic link library). In order to use one of these objects, you must know the name of the assembly in which it is stored. Then you must add a reference to that assembly in your application.

To add a reference to an assembly, on the main menu, you can click Project -> Add Reference... You can also right-click the automatically created References node in Solution Explorer and click Add Reference... Any of these actions would display the Add Reference dialog box from where you can click the reference, click Select and click OK. If you don't see the reference you are looking for, you can locate it on another drive or directory using the Browse button.

There are two broad categories of objects used in a Windows Forms application: the forms and the controls. A form is the most fundamental object used on an application. It is a rectangular object that uses part of the computer desktop to represent an application. A form is based on the Form class that is defined in the System.Windows.Forms namespace created in the System.Windows.Forms.dll assembly. Every GUI application you will create starts with a form. There are various techniques you can use to get a form in your application:

  • You can programmatically and manually create a form
  • You can inherit a form from the Form class
  • You can create a form based on another form that either you or someone else created already, etc.

The primary means of getting a form into an application consists of deriving one from the Form class.

Practical LearningPractical Learning: Deriving a Form From the Form Class

  1. To add a reference to the assembly in which the Form class is defined, on the main menu, click Project -> Add Reference...
  2. In the Add Reference dialog box, click the .NET tab if necessary and scroll down in the list
  3. Click System
  4. Press and hold Ctrl
  5. Click System.Windows.Forms
     
    Add Reference
  6. Click OK
  7. To inherit a form from the Form class, change the file as follows:
     
    using System;
    using System.Windows.Forms;
    
    public class Starter : Form
    {
        public static int Main()
        {
            return 0;
        }
    }
  8. Save the file

The Application Class

The form is the object that gives presence to an application. Once you have created the (primary) form of your application, you can get it ready to display on the screen. This is taken care of by the Application class equipped to start an application, process its messages or other related issues, and stop the application.

The Application class provides the overloaded Run() method that can be used to start a program. One of the versions of this method takes a form as argument. This form must be the first, main or primary form of your application; it will be the first to display when the application comes up.

Practical LearningPractical Learning: Using the Application Class

  1. To prepare the application for starting, change the Main() method as follows:
     
    using System;
    using System.Windows.Forms;
    
    public class Starter : Form
    {
        public static int Main()
        {
            // Instantiate an Program object
            Starter frmMain;
    
            // Allocate memory for the object, using the new operator
            frmMain = new Starter();
            // Call the Run() static method of the Application
            // and pass it the instance of the class to display
            Application.Run(frmMain);
    
            // Everything went alright... We hope
            return 0;
        }
    }
  2. Test the application
     
    Form
  3. Close it by clicking its system Close button and return to your programming environment

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 Return Value of a Message Box

Besides displaying a message, a message box is may be meant to let the user make a decision by clicking a button and, 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 are defined in the DialogResult enumeration. 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 Message of a Message Box

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, you can call the Show() static method of this class. 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:

public class Program
{
    static int Main()
    {
        MessageBox.Show("Welcome to the Wonderful World of Visual C#");
        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.

The Caption of a Message Box

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:

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

This would produce:

Message Box

The Buttons of a Message Box

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 enumeration. 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 enumeration and access the desired combination. Here is an example:

public class Program
{
    static int Main()
    {
        MessageBox.Show("Welcome to the Wonderful World of Visual C#",
                            "Visual C# Tutorials",
                            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 Information
Error Critical
Exclamation Exclamation
Hand Critical
Information  Information
Question Question
Stop Critical
Warning Exclamation

Here is an example:

public class Program
{
    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);
        return 0;
    }
}

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 Program
{
    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.Button1);
        	return 0;
    }
}
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:

public class Program
{
        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.Button2);
        	return 0;
        }
}
Message Box With an Icon

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

public class Program
{
    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);
        return 0;
    }
}
Message Box With an Icon
 

The Project Interface

 

Introduction

Besides the windows and functionalities we reviewed earlier, when you work on a project, there are other features that become available.

The Server Explorer

The Server Explorer is an accessory that allows you to access SQL Server databases without using the physical server and without opening Microsoft SQL Server:

Server Explorer

The items of this window display in a tree. To expand a node, you can click its + button. To collapse it, click its - button.

The Solution Explorer

The Solution Explorer is a window that displays the file names and other items used in your project:

Solution Explorer

The items of this window display in a tree. To expand a node, you can click its + button. To collapse it, click its - button. To explore an item, you can double-click it. The result depends on the item you double-clicked.

The Solution Explorer can be used to create a new class, a new folder, or a reference. To perform any of these operations, you can right-click a folder node such as the name of the project, position the mouse on Add and select the desired operation. You can also perform any of these operations from the Project category of the main menu.

Besides adding new items to the project, you can also use the Solution Explorer to build the project or change its properties. If you add one or more other project(s) to the current one, one of the projects must be set as the default. That project would be the first to come up when the user opens the application. By default, the first project created is set as the default. If you have more than one project, to set the default, right-click the name of the desired project in Solution Explorer and click Set As StartUp Project.

The Solution Explorer also you to rename or delete some of the items that belong to your project.

Practical LearningPractical Learning: Using the Solution Explorer

  1. To start a new project, on the main menu, click File -> New -> Project...
  2. In the Templates list, click Empty Project and change the Name to Exercise3
  3. Click OK
  4. On the main menu, click Project -> Exercise3 Properties...
  5. In the left frame, make sure Application is selected.
    In the right frame, click the arrow of the Output Type combo box and select Windows Application
  6. If the Solution Explorer is not visible, on the main menu, click View -> Solution Explorer.
    In the Solution Explorer, right-click Exercise3 and click Add Windows Form...
  7. In the Templates list, make sure Windows Form is selected.
    Set the Name to Exercise and click Add

The Class View

The Class View displays the various classes used by your project, including their ancestry. The items of the Class View are organized as a tree list with the name of the project on top:

Class View

The Class View shares some of its functionality with the Solution Explorer. This means that you can use it to build a project or to add new class.

While the Solution Explorer displays the items that are currently being used by your project, the Class View allows you to explore the classes used in your applications, including their dependencies. For example, sometimes you will be using a control of the .NET Framework and you may wonder from what class that control is derived. The Class View, rather than the Solution Explorer, can quickly provide this information. To find it out, expand the class by clicking its + button.

Practical LearningPractical Learning: Using the Class View

  1. If the Class View is not visible, on the main menu, click View -> Class View.
    In the Class View, expand the Exercise2 node if necessary
  2. Right-click the name of the project Exercise3 -> Add -> Class...
  3. In the Templates list, make sure Class is selected. Change the Name to Central and click Add
  4. Change the file as follows:
     
    using System;
    using System.Windows.Forms;
    
    namespace Exercise3
    {
        public class Central
        {
            public static int Main()
            {
                Application.Run(new Exercise());
    
                return 0;
            }
        }
    }
  5. Execute the application to see the new form

Fundamentals of Control Addition

 

The Client Area

On a form, the client area is the body of the form without the title bar, its borders and other sections we have not mentioned yet such as the menu, scroll bars, etc:

Client Area

 

Besides the form, every control also has a client area. The role of the client area is to specify the bounding section where the control can be accessed by other controls positioned on it. Based on this, a control can be visible only within the client area of its parent. Not all controls can be parent.

Design and Run Times

Application programming primarily consists of adding objects to your project. Some of these objects are what the users of your application use to interact with the computer. As the application developer, one of your jobs will consist of selecting the necessary objects, adding them to your application, and then configuring their behavior. There are various ways you can get a control into your application. If you are using Notepad or a text editor to add the objects, you can write code. If you are using Microsoft Visual C#, you can visually select an object and add it.

To create your applications, there are two settings you will be using. If a control is displaying on the screen and you are designing it, this is referred to as design time. This means that you have the ability to manipulate the control. You can visually set the controlís appearance, its location, its size, and other necessary or available characteristics. The design view is usually the most used and the easiest because you can glance at a control, have a realistic display of it and configure its properties. The visual design is the technique that allows you to visually add a control and manipulate its display. This is the most common, the most regularly used, and the easiest technique.

The other technique you will be using to control a window is with code, writing the program. This is done by typing commands or instructions using the keyboard. This is considered, or referred to, as run time. This is the only way you can control an objectís behavior while the user is interacting with the computer and your program.

The Toolbox

 

Introduction

A Windows control is a graphical object that allows the user to interact with the computer. The controls are as varied as the needs and goals are. Because there are so many controls for various purposes, their insertion to an application and their configuration are left to the computer programmer. The Toolbox is the accessory that provides most of the controls used in an application:

Toolbox

By default, the Toolbox is positioned on the left side of the IDE. To change that position, you can drag its title bar away and dock it to another side of the IDE. The Toolbox also uses a default width to show the items on it. If the width is too narrow or too wide, you can change it. To do this, position the mouse to its right border and drag left or right.

The Toolbox and Additional Controls

When Microsoft Visual Studio is set up, it installs in the Toolbox the most regularly used controls. If you are working in an environment that creates only a particular group of applications and there are controls you hardly use, if you want, you can remove them from the list. To remove a control, right-click it and click Delete.

Besides the objects in the Common Controls section, other controls are left out but are still available. Some of the left out controls were created with the .NET Framework but are not installed by default because they are judged hardly used. To add one or more of these left out controls, right-click anywhere in the Toolbox and click Choose Items... In the Choose Toolbox Items dialog box, click the .NET Framework Components tab, then click the check box of the desired control before clicking OK:

Choose Toolbox Items

In addition to custom .NET controls, some other objects called ActiveX controls were used in previous versions of Visual Basic or Visual Studio and are available. To take care of compatibility issues, most previous ActiveX controls were reconfigured and adapted to be used in a .NET application. To add some of these left out controls, right-click anywhere in the Toolbox and click Choose Items... In the Choose Toolbox Items dialog box, click the COM Components tab, select the desired control before clicking OK

Choose Toolbox Items

The Sections of the Toolbox

When you start a Windows Forms Application, it provides various controls on the Toolbox so you can choose which ones are appropriate for your particular application. Controls can be set by categories based on their function or role. A container is a control whose main purpose is to host other controls. To design it, you pick up objects from the Toolbox and drop them where desired. The Toolbox organizes its items in categories and each category is represented by a button:

Toolbox

If the available list of categories is not enough, you can add a new section of your choice. By default, Visual Studio hides some categories because they are judged hardly used. To display these additional sections, you can right-click anywhere in the Toolbox and click Show All:

Toolbox

If you still want an additional tab not included in the list, you can add one (or more). To do that, right-click anywhere in the Toolbox and click Add Tab. You would be prompted to provide a name. After typing the new name, press Enter.

The Layout of a Category

To use an object of a particular category, you can first click its button. After selecting a category, it displays its items. In each category, a particular button called Pointer is selected by default. This simply indicates that no item in the group is currently selected.

By default, the items in each category are organized as horizontal wide buttons:

Toolbox

Alternatively, you can list the items of a category as buttons of a list view. To do that, you can right-click anywhere in the category and click List View to remove its check box:

 

Arrangement of Items in the Toolbox

When Microsoft Visual Studio is installed, it adds the buttons in a somewhat random order. In the beginning, this can make it difficult to find a particular control when you need it. If you find it more convenient, you can arrange the list of controls in any order of your choice. You have two main options. To change the position of an item in the list, right-click it and click either Move Up or Move Down. Alternatively, you can arrange the items in alphabetic order. To do that, right-click anywhere in the Windows Forms section and click Sort Items Alphabetically:

Toolbox

Once you have rearranged items alphabetically, the Toolbox forgets the previous arrangement and you cannot restore it. Alternatively, you can right-click the button of a control and click either Move Up or Move Down.

 
 

Previous Copyright © 2008-2009, yevol.com Next