Lesson 2: Using Forms

Lesson 2: Using Forms

As noted in Lesson 1, forms are the fundamental unit of your user interface. They provide a backdrop that hosts the controls, and they allow you to present your application in a consistent and attractive manner. Forms can display data and receive user input. Although it is possible to create an application, such as a Windows service or a console application, that has no forms at all, applications designed for frequent user interaction usually contain at least one form. Applications that are more complex often require several forms to allow the program to flow in a consistent and logical manner.

After this lesson, you will be able to

  • State the role of forms in an application

  • Explain how to add forms to your application

  • Explain how to set the start-up form and the start-up location

  • Explain how to set the visual appearance of your form

  • Explain how to use form methods

  • Explain how to use form events

Estimated lesson time: 30 minutes

Adding Forms to Your Project

Forms enable interaction between your application and a user. When you create a new Windows Forms project, an initial form, named Form1, is added by default. Form1 is not an actual instance of a form, however, but rather a class that represents the code behind an instance of a form. You can edit Form1 by adding controls, menus, and other visual elements in the designer. The designer is a graphic representation of the designable component (usually a form) that you are creating, and it provides the ability to add controls to your form by dragging them from the tool box to the design surface represented on the screen. While designing a form or other component, you are said to be at design-time. As your application grows in size, you will want to add additional form classes to your project.

To add a new form to a project

  1. On the Project menu, click Add Windows Form. The Add New Item dialog box opens.

  2. Click Windows Form, and click Open. A new form is added to the development environment.

You can also add a new form using code. In this case, you declare a variable that represents a type of form and creates an instance of that form. This form can be used and displayed during execution of your application. Note that you will be unable to use any design tools to create this form, and it will be unavailable at design time. The code method is often employed when you want to display a form that already exists.

To add a form to your application at run time

Declare and instantiate a variable representing your form in the same manner as you would any other class. For example:

Visual Basic .NET

' This example assumes that you have already designed a form ' called DialogForm Dim myForm As DialogForm myForm = New DialogForm()

Visual C#

// This example assumes that you have already designed a form // called DialogForm DialogForm myForm; myForm = new DialogForm();

Visual Inheritance

Visual inheritance is a means of creating forms that are closely related. The technique allows you to create a form that incorporates all the members, controls, menus, and code associated with an existing form, and to use the new form as a base for additional functionality. Thus, you can create a single form that incorporates elements common to the entire interface and then individually tailor each form for its specific purpose. You can use either the Inheritance Picker or code to create the inheritance relationship. Inheritance is discussed in greater detail in Chapter 4.

To create an inherited form with the Inheritance Picker

  1. From the Projects menu, select Add Inherited Form. The Add New Item dialog box opens.

  2. In the left pane of the dialog box, choose Local Project Items. In the right pane, select Inherited Form. Name this form in the Name box, and click Open to open the Inheritance Picker.

  3. The forms in your project are displayed in the Inheritance Picker. If the form from which you want to inherit is one of these forms, choose it and click OK. A new inherited form is added to your project.

    If you want to inherit from a form outside of your project, click Browse. Navigate to the project containing the form you want. Click the DLL file containing the form, and click Open.

    You now return to the Inheritance Picker dialog box, where the selected project is now listed. Choose the appropriate form, and click OK. A new inherited form is added to your project.

    NOTE
    To use the Inheritance Picker, the form from which you want to inherit must be in the project or compiled in an EXE or DLL file.

To create an inherited form in code

  1. From the Projects menu, select Add Windows Form. A new form class is added to your project.

  2. Open the code editor for your new form by right-clicking the form in Solution Explorer and choosing View Code. Modify the class declaration (Visual C#) or use the Inherits keyword (Visual Basic .NET) to specify the inherited form, as indicated by the following example:

    Visual Basic .NET

    ' This example assumes that you are inheriting from a form class ' named MainForm and that that form resides in your project Public Class myForm Inherits MainForm ' Additional class implementation omitted End Class

    Visual C#

    // This example assumes that you are inheriting from a form class // named MainForm, and that that form resides in your project public class myForm : MainForm { // Additional class implementation omitted }

    NOTE
    To use inheritance in code, as shown in the preceding example, your project must be able to refer to that form. Thus, it must include either a reference to the assembly that contains the form from which you want to inherit (in this example, MainForm), or that form must be a member of your project.

Setting the Start-Up Form

If your Windows Forms application contains multiple forms, you must designate one as the start-up form. The start-up form is the first form to be loaded on execution of your application. In Visual Basic .NET, you can designate a form as the start-up form by setting the start-up object for your application, which is done in the Properties window, as shown in Figure 2.1.

figure 2-1 the visual basic .net project properties window.

Figure 2-1. The Visual Basic .NET project Properties window.

To set the start-up form in Visual Basic .NET

  1. In Solution Explorer, click the name of your project. The project name is highlighted.

  2. From the Project menu, choose Properties.

  3. Under Startup Object, choose the appropriate form from the drop-down menu.

Setting the start-up form in Visual C# is slightly more complicated. To act as a start-up object, your form must have a method named Main that serves as the starting point for the application. The Main method specifies the application start-up form. For example, a Main method that specifies a form named myForm looks like this:

Visual C#

static void Main() { Application.Run(new myForm()); }

From the project Properties window, you can choose any form that has an appropriate Main method as the start-up form, as shown in Figure 2.2.

figure 2-2 the visual c# project properties window.

Figure 2-2. The Visual C# project Properties window.

To set the start-up form in Visual C#

  1. In Solution Explorer, click the name of your project. The project name is highlighted.

  2. From the Project menu, choose Properties.

  3. Under Startup Object, choose the appropriate form from the drop-down menu. The selected form must contain a suitable Main method that specifies the correct start-up object.

Setting the Start-Up Location

You can use the form s StartPosition property to determine where on the computer screen the form will open when first displayed. The StartPosition property can be set to any of the values contained within the FormStartPosition enumeration. The FormStartPosition enumeration values are listed in Table 2.1.

Table 2-1. FormStartPosition Property Settings

FormStartPosition Setting

Effect

Manual

The form opens at the location determined by the form s Location property.

CenterScreen

The form opens centered in the screen.

WindowsDefaultLocation

The form opens at the Windows default location.

WindowsDefaultBounds

The form opens at the Windows default location and at the Windows default bounding size.

CenterParent

The form opens centered on its parent form.

To set the start-up position for a form

In the project s Properties window, change the StartPosition property to the desired setting.

Changing the Appearance of Your Form

The way your user interface looks is an important part of your application. A user interface that is poorly designed is correspondingly difficult to learn and, therefore, increases training time and expense. The use of properties allows you to manipulate the appearance of your forms.

A form has many inherent properties that affect its appearance. You can view and change these properties in the Properties window of the designer, as shown in Figure 2.3.

figure 2-3 change inherent properties in the properties window.

Figure 2-3. Change inherent properties in the Properties window.

Some properties, such as Font, are actually structures with several values that affect the behavior of a form. You can see each of these values and change them as desired by clicking the plus sign (+) next to the Font property in the Properties window. Some properties, such as BackColor and ForeColor, supply an editor to assist in choosing a value.

A form s properties also can be changed at run time in code. For example, if you want the background color to change to red, you would add the following line to your code:

Visual Basic .NET

' This assumes that you want to change the color of a previously ' created form called MyForm MyForm.BackColor = System.Drawing.Color.Red

Visual C#

// This assumes that you want to change the color of a previously // created form called MyForm MyForm.BackColor = System.Drawing.Color.Red;

Properties follow the same general syntax as other class members. You use the assignment operator (=) to assign a value to a property, and you use the property name to reference its value.

BackColor, ForeColor, and Text Properties

Users will be immediately aware of BackColor, ForeColor, and Text properties. The Text property indicates the caption of the form. The BackColor and ForeColor properties represent the colors of a form. ForeColor is the color of text in the foreground. Most controls have their ForeColor set to the ForeColor of the form when they are added to the form. BackColor represents the background color of the form. Many controls, such as Button and Label, have their BackColor set to match the form when they are added in the designer. Other controls, such as TextBox, have independent settings that must be changed manually.

Use caution when choosing colors. Red text on a blue background might look attractive while you re designing, but it can be hard to read once your application is deployed. High-contrast color schemes offer the best choice for readability.

Font, Cursor, and BackGroundImage

The Font, Cursor, and BackGroundImage properties are tools to help you vary the look of your interface in additional ways. The Font property allows you to specify the font you want to use for your form. Once set, the font is applied to the form controls to give the form a consistent look and feel. The Cursor property allows you to specify the icon that appears when a mouse pointer is over your form. BackGroundImage allows you to set the background as an image instead of a color. If you set a background image, changing the BackColor property will not affect the form itself, but it will change the BackColor of any form controls.

Opacity

You can create striking visual effects for your form by altering its transparency with the Opacity property controls. Opacity values range between 0 and 1. A value of 1 indicates that a form is completely opaque, and a value of 0 creates a completely transparent form. Any value between the two settings results in a partially transparent form. An Opacity of 1 (fully opaque) is the default value. The Opacity property is useful when it is necessary to keep one form in the foreground but monitor action in a background form. Generally, a control inherits the opacity of the form that hosts it.

To create a transparent or translucent form

Set the Opacity property to a value less than 1.

Visual Basic .NET

' Creates a half-transparent form MyForm.Opacity = .5 

Visual C#

// Creates a half-transparent form MyForm.Opacity = .5;

In the Properties Window (as opposed to code), Opacity is represented as a percentage value. Thus, when setting Opacity, you should select a value between 0 percent and 100 percent.

Using Form Methods

A method performs an action, and classes incorporate member methods that perform functions relevant to that class. Every form encapsulates a base set of functionality inherited from the System.Windows.Forms.Form class. Included in this functionality are several methods for managing how your forms are displayed and accessed in the user environment. Some of these methods are

  • Form.Show

  • Form.ShowDialog

  • Form.Activate

  • Form.Hide

  • Form.Close

In order to use any of these methods, you must have a reference to a form available, which means that the form must be already instantiated and must exist in memory. In addition to instances of forms you create in code, your application also creates an instance of your start-up form when program execution begins.

When writing code inside a form class, you can refer to the current instance of that form by using the Me (Visual Basic .NET) or this (Visual C#) keyword. For example, suppose you want to write a method that changes your form s Text value. Because you are writing code that will affect a particular instance of the form, the only way to refer to it is with the special keyword, as shown in the following code:

Visual Basic .NET

' This line changes the text of the current instance Me.Text = "This is the active form"

Visual C#

// This line changes the text of the current instance this.Text = "This is the active form";

Show and ShowDialog

For a form to be useful, it must be visible. To make a form visible, you can call the Form.Show method. This method causes an instance of a form class to load into memory, display on the screen, and receive the focus of the application. The Visible property is set to true when Form.Show is called. If a form is already loaded into memory and is simply not visible (if the Visible property has been set to false, for instance), calling Form.Show has essentially the same effect as setting the Visible property to true.

Form.ShowDialog accomplishes everything that Form.Show does, and it displays the form as a modal dialog box, which means that the form must be closed before any other form can receive the focus. Displaying your form modally allows you to force the user to complete any tasks on that form before continuing with the rest of the program. This method of displaying a form should be used when it is crucial that the user completes a specific action. For example, you might use Form.Show Dialog to inform the user that a floppy drive is inaccessible, or to prompt for a password. The following code demonstrates the use of these methods:

Visual Basic .NET

' This example assumes that you have created a Form class called ' DialogForm Dim myForm as New DialogForm() ' Shows the form regularly myForm.Show() ' Shows the form modally myForm.ShowDialog()

Visual C#

// This example assumes that you have created a Form class called // DialogForm DialogForm myForm = new DialogForm(); // Shows the form regularly myForm.Show(); // Shows the form modally myForm.ShowDialog();

Activate

If a form is already visible but does not currently have the focus, you can use the Form.Activate method. When called in the active application, the Form.Activate method moves the form to the front of the application and assigns it the focus. If this method is called in an application that is not currently active in the user interface, it causes the window caption to flash in the taskbar. The form must be visible for this method to have any effect. If called on a form that is not yet visible, this method will do nothing at all.

Visual Basic .NET

myForm.Activate()

Visual C#

myForm.Activate();

Hide

The Form.Hide method removes a form from view. Although the form still exists in memory, it is no longer be visible until the Form.Show method is called or the form s Visible property is set to true in code. Calling this method sets the form s Visible property to false and essentially has the same effect.

Visual Basic .NET

myForm.Hide()

Visual C#

myForm.Hide();

Close

When you are finished with a form, you can call the Form.Close method to close the form and remove it from memory. This method closes all resources contained within the form and marks them for garbage collection (discussed in Chapter 1). Once you have called Form.Close, you cannot call Form.Show to make the form visible again because the resources for the form are no longer available. If you call Form.Close on the start-up form of your application, the application closes.

Visual Basic .NET

myForm.Close()

Visual C#

myForm.Close();

Using Form Events

An event represents something interesting happening in the program. When an event takes place, the application raises that event and other components of the application have the opportunity to handle that event. Each of the aforementioned methods raises one or more events when called. As a developer, you are afforded the opportunity to write code that allows your application to respond to that event and execute code (also known as handling the event). Although events and event handlers are discussed in greater detail in Chapter 3, now is a good time to introduce creating and using event handlers.

Each control and form can raise a variety of different events that correspond to events in application execution. For example, when the Form.Hide method is called, the form raises the Deactivate event and the VisibleChanged event. If you want the application to take any kind of action when an event occurs, you can create an event handler, which is a method that executes in response to a raised event. You might, for example, place code in a Deactviate event handler to ensure that all required fields on a form have been filled in.

You can create an event handler using the Visual Studio .NET user interface. You can also create an event handler directly in code, but this method is more complicated and will be covered in Chapter 3. Visual Basic .NET and Visual C# use slightly different methods for creating an event handler.

To create an event handler with Visual Basic .NET

  1. In the Code Editor view, choose (Base Class Events) from the Class Name drop-down menu at the top of the code editor.

    NOTE
    If you want to create an event handler for a control on the form, you should choose that control instead of (Base Class Events).

  2. In the Method Name drop-down menu, choose the event for which you want to write code.

    A default event handler is added to your code editor. You can now write code in this method, which will execute when this event is raised. Figure 2.4 shows the Class Name and Method Name lists.

    figure 2-4 adding an event handler in visual basic .net.

    Figure 2-4. Adding an event handler in Visual Basic .NET.

To create an event handler with Visual C#

  1. In Design view, use the mouse to select the form or control for which you want to create an event handler.

  2. In the Properties window, click the Events button. A list of available events is displayed in the Properties window.

  3. Find the event for which you want to write a handler, and double-click it.

    The Code Editor view opens to a newly created event handler for that event. You can now add code to this method, which will execute when the event is raised. Figure 2.5 shows the events in the Properties window. Note the Events button, which looks like a lightning bolt or spark.

    figure 2-5 adding an event handler in visual c#.

    Figure 2-5. Adding an event handler in Visual C#.

Event Arguments

As with every method, each event handler has a signature. For example, consider the following method:

Visual Basic .NET

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles MyBase.Load ' Code for the method goes here End Sub

Visual C#

private void Form1_Load(object sender, System.EventArgs e) { // Code for the method goes here }

In this method, two arguments are passed to the method by the object (Form1 in this case) that raises the event. The arguments are sender, which is an object that contains a reference to the object that raised the event, and e, which is an instance of the EventArgs class. If you know the type of object that raised the event, you can obtain a reference to it by explicitly casting sender to the correct type. For example:

Visual Basic .NET

Dim myForm As Form1 myForm = CType(sender, Form1)

Visual C#

Form1 myForm; myForm = (Form1)sender;

The EventArgs argument represents any other arguments that need to be passed from the object to the event handler. In many cases, the EventArgs parameter contains no programmatically useful information. In some cases, however, arguments that are useful or even required by the method will be passed in this parameter. For example, as you will see shortly, the Form.Closing event passes an instance of CancelEventArgs to its event handler, which can be used to cancel the form s closing. All events raised by forms and controls pass a sender reference and some variety of EventArgs to their event handler.

Form Lifetime Events

Various events are raised throughout a form s lifetime. In this section, we will examine some of the events that are raised as a form is created, manipulated, and destroyed. The events we will examine are

  • Load

  • Activated/Deactivate

  • VisibleChanged

  • Closing

  • Closed

Although this list is not exhaustive of the events a form can raise, it is representative of the normal events that typically occur during a form s lifetime.

Load

The Load event is fired when an instance of a form is first loaded into the program. This event is raised the first time that the Form.Show or Form.ShowDialog method is called for each instance of a form. Consider the following example:

Visual Basic .NET

Dim myForm as New Form() myForm.Show() ' The Load event fires here myForm.Hide() ' Form is now invisible myForm.Show() ' The Load event doesn't fire again myForm.Close() ' Closes and disposes the form myForm.Show() ' Throws an exception because myForm ' is no longer available

Visual C#

Form myForm = new Form(); myForm.Show(); // The Load event fires here myForm.Hide(); // Form is now invisible myForm.Show(); // The Load event doesn't fire again myForm.Close(); // Closes and disposes the form myForm.Show(); // Throws an exception because myForm // is no longer available

This example demonstrates when the Load event is raised. Note that it is raised only once in the lifetime of a particular form object. If you have multiple instances of a single form, the Load event is raised once per instance. You can use a handler for the Load event to initialize variables for a form and prepare it for use.

Activated/Deactivate

The Activated event can fire several times in a form s lifetime. It is raised whenever the form receives the focus. Thus, it is raised when Form.Show or Form.ShowDialog is called, as well as when Form.Activate is called or when a form is brought to the front of the application. You might use the Activated event handler to set the focus to a particular control on a form or to change the color to indicate that the form is active.

The Deactivate event is raised whenever the current form loses the focus. A form can lose the focus through user interaction with the interface or when the Form.Hide or Form.Close methods are called (although Form.Close raises this event only if the form being closed is the active form). You might use this event to validate user input.

Both the Activated and Deactivate events fire only when the focus is changed within the program. If you click another application and then return to your .NET program, neither event fires.

VisibleChanged

As the name implies, the VisibleChanged event is raised whenever the visible property of the form is changed. Thus, this event is raised whenever the form is made visible or invisible. The form methods that cause this event to be raised include Form.Show, Form.ShowDialog, Form.Hide, and Form.Close.

Closing

The Closing event is raised when the current form is in the process of closing but has not yet fully closed. This event is raised by calling the Form.Close method or by the user clicking the Close button on the form. You can use this event to verify that all tasks required by a particular form have been completed. For example, it can verify that all the fields of a form have been filled out.

The Closing event handler signature includes an instance of CancelEventArgs. You can abort the form closing and cause the form to remain open by setting the Cancel property of this instance to True, as shown in the following example:

Visual Basic .NET

Private Sub Form1_Closing(ByVal sender As Object, ByVal e As _ System.ComponentModel.CancelEventArgs) Handles MyBase.Closing e.Cancel = True End Sub

Visual C#

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e) { e.Cancel = true; }

Closed

The Closed event is raised after a form has been closed. Like the Closing event, this event is raised by calling Form.Close or by the user manually closing a form. The Closed event is raised after the Closing event is raised and any handlers for the Closing event are executed. Use the Closed event to provide any necessary clean-up code.

Lesson Summary

  • Forms are the primary unit of the user interface for a Windows Forms program. You should manage your forms in such a manner as to present a consistent, complete, and attractive visual interface to the end user. You can add forms to your application at design time or at run time, and you can use visual inheritance to create several forms with similar looks and layouts.

  • Forms have properties that control their appearance. Changing these properties changes the appearance of the form and sometimes the controls hosted by the form. These properties include

    • BackColor

    • ForeColor

    • Text

    • Font

    • Cursor

    • BackGroundImage

    • Opacity

  • Forms have several intrinsic methods that you can use to control their lifetime and how they are displayed. Among them are

    • Form.Show

    • Form.ShowDialog

    • Form.Activate

    • Form.Hide

    • Form.Close

  • Each of these methods causes change in the visual interface and raises various events. These events include

    • Load

    • Activated/Deactivate

    • VisibleChanged

    • Closing

    • Closed

  • You can create specialized methods called event handlers that respond to events. These methods are executed whenever the corresponding event is raised.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[.  .. ]0-316
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[. .. ]0-316
ISBN: 735619263
EAN: N/A
Year: 2003
Pages: 110

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net