User:Foxall/05

Ka Wiktionary

./ ADD NAME=CH05.HTM

[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/part02.htm Previous Section] [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch05lev1sec1.htm Next Section]

Hour 5. Building Forms�Part I

With few exceptions, forms are the cornerstone of every Windows application's interface. Forms are essentially windows and the two terms are often used interchangeably. More accurately, "window" refers to what's seen by the user and what the user interacts with, whereas "form" refers to what you see when you design. Forms let users view and enter information in a program (such as the form you built in your Picture Viewer program in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch01.htm#ch01 Hour 1], "A C# Programming Tour"). Such information may be text, pictures, graphs�almost anything that can be viewed onscreen. Understanding how to design forms correctly will enable you to begin creating solid interface foundations for your programs.

graphics/bookpencil.gif C# uses a new forms engine called Windows Forms.

Think of a form as a canvas on which you build your program's interface. On this canvas, you can print text, draw shapes, and place controls with which users can interact. The wonderful thing about C# forms is that they behave like a dynamic canvas; not only can you adjust the appearance of a form by manipulating what's on it, you can also manipulate specific properties of the form itself.

In previous hours, you manipulated the following form appearance properties:

  • Text
  • Height
  • Left
  • Top
  • Width

The capability to tailor your forms, however, goes far beyond these simple manipulations.

There is so much to cover about Windows Forms that I've broken the material into two hours. In this hour, you'll learn the very basics of forms�adding them to a project, manipulating their properties, and showing and hiding them using C# code. Although you've done some of these things in previous hours, here you'll learn the nuts and bolts of the tasks you've performed. In the following hour, you'll learn more advanced form techniques.

The highlights of this hour include the following:

  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch05lev1sec1.htm#ch05lev1sec1 Changing the name of a form]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch05lev1sec2.htm#ch05lev1sec2 Changing the appearance of a form]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch05lev1sec2.htm#ch05lev2sec1 Displaying text on a form's title bar]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch05lev1sec2.htm#ch05lev2sec3 Adding an image to a form's background]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch05lev1sec2.htm#ch05lev2sec4 Giving a form an icon]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch05lev1sec2.htm#ch05lev2sec5 Preventing a form from appearing in the taskbar]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch05lev1sec2.htm#ch05lev2sec8 Specifying the initial display position of a form]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch05lev1sec2.htm#ch05lev2sec9 Displaying a form in a normal, maximized, or minimized state]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch05lev1sec2.htm#ch05lev2sec10 Changing the mouse pointer]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch05lev1sec3.htm#ch05lev1sec3 Showing and hiding forms]
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/part02.htm Previous Section] [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch05lev1sec1.htm Next Section]
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/05.htm#toppage Top]

./ ADD NAME=CH05LEV1SEC1.HTM

[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch05.htm Previous Section] [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch05lev1sec2.htm Next Section]
 Changing the Name of a Form 

The first thing you should do when you create a new object is give it a descriptive name, so that's the first thing I'll talk about in this hour. Start C# now (if it's not already running) and create a new Windows Application titled Forms Example. Using the Properties window, change the name of the form to fclsExample. When you need to create a new instance of this form, you'll use this name rather than the default generic name of Form1.

graphics/bulb.gif Remember, when you change the name of the startup form for your application, you need to update the class name in the entry point of your application (static void Main()). Refer to [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch01.htm#ch01 Hour 1] for instructions on how to do this.

Changing the Appearance of a Form

Take a moment to browse the rest of the form's properties in the Properties window. In this hour, I'll show you how to use the more common properties of the form to tailor its appearance.

graphics/bulb.gif Remember, to get help on any property at any time, select the property in the Properties window and press F1.
Displaying Text on a Form's Title Bar 

You should always set the text in a form's title bar to something meaningful. (Note: Not all forms have title bars, as you'll see later in this hour.) The text displayed in the title bar is the value placed in the form's Text property. Generally, the text should be one of the following:

  • The name of the program. This is most appropriate when the form is the program's main or only form.
  • The purpose of the form. This is perhaps the most common type of text displayed in a title bar. For example, if a form is used to select a printer, consider setting the Text property to Select Printer. When you take this approach, use active voice (for instance, don't use Printer Select).
  • The name of the form. If you choose to place the name of the form into the form's title bar, use the "English" name, not the actual form name. For instance, if you've used a naming convention and named a form fclsLogin, use the text Login or Login Form.

Change the Text property of your form to Building Forms Example. Your form should now look like the one in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/05.htm#ch05fig01 Figure 5.1].

Figure 5.1. Use common sense when setting title bar text.

graphics/05fig01.jpg

graphics/bookpencil.gif As with most other form properties, you can change the Text property at any time using C# code.
Changing a Form's Background Color 

Although most forms appear with a gray background (this is part of the standard 3D color scheme in Windows), you can change a form's background to any color you like. To change a form's background color, you change its BackColor property. The BackColor property is a unique property in that you can specify a named color or an RGB value in the format Red, Green, Blue.

By default, the BackColor is set to the color named Control. This color is a system color and may not be gray. When Windows is first installed, it's configured to a default color scheme. In the default scheme, the color for forms and other objects is the familiar "battleship" gray. However, as a Windows user, you're free to change any system color you desire. For instance, some people with color blindness prefer to change their system colors to colors that have more contrast than the defaults so that objects are more clearly distinguishable. When you assign a system color to a form or control, the appearance of the object adjusts itself to the current user's system color scheme. This doesn't just occur when a form is first displayed; changes to the system color scheme are immediately propagated to all objects that use the affected colors.

Change the background color of your form to blue now by deleting the word Control in the BackColor property in the Properties window; in its place enter 0,0,255 and press Enter or Tab to commit your entry. Your form should now be blue because you entered an RGB value in which you specified no red, no green, and maximum blue (color values range from 0 to 255). In reality, you'll probably rarely enter RGB values. Instead, you'll select colors from color palettes. To view color palettes from which you can select a color for the BackColor property, click the drop-down arrow in the BackColor property in the Properties window (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/05.htm#ch05fig02 Figure 5.2]).

Figure 5.2. All color properties have palettes from which you can choose a color.

graphics/05fig02.jpg

graphics/bookpencil.gif System colors are discussed in detail in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch10.htm#ch10 Hour 10], "Drawing and Printing."

When the drop-down list appears, the color Blue on the Web tab is selected. This occurs because when you entered the RGB value 0,0,255, C# looked for a named color composed of the same values and it found blue. The color palettes were explained in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch02.htm#ch02 Hour 2], "Navigating C#," so I'm not going to go into detail about them here. For now, select the System tab to see a list of the available system colors and choose Control from the list to change the BackColor of your form back to the default Windows color.

 Adding an Image to a Form's Background 

In addition to changing the color of a form's background, you can also place a picture on it. To add a picture to a form, set the form's BackgroundImage property. When you add an image to a form, the image is "painted" on the form's background. All the controls that you place on the form appear on top of the picture.

Add an image to your form now by following these steps:

  1. Select the form.
  2. Click the BackgroundImage property in the Properties window.
  3. Click the Build button that appears next to the property (the small button with three dots).
  4. Use the Open dialog box that appears to locate and select an image file from your hard drive. (I used Blue Lace 16.BMP, which I found in my \WinNT folder.)

C# always tiles an image specified in a BackgroundImage property (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/05.htm#ch05fig03 Figure 5.3]). This means that if the selected picture isn't big enough to fill the form, C# will display additional copies of the picture, creating a tiled effect. If you want to display a single copy of an image on a form, anywhere on the form, you should use a picture box, as discussed in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch10.htm#ch10 Hour 10].

Figure 5.3. Images are tiled to fill the form.

graphics/05fig03.jpg

Notice that to the left of the BackgroundImage property is a small box containing a plus sign. This indicates that there are related properties, or subproperties, of the BackgroundImage property. Click the plus sign now to expand the list of subproperties (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/05.htm#ch05fig03 Figure 5.3]). In the case of the BackgroundImage property, C# shows you a number of properties related to the image assigned to the property, such as its dimensions and image format.

graphics/bulb.gif Adding background images to forms can add pizzazz to a program, but it can also confuse users by making forms unnecessarily busy. Try to avoid adding images just because you can. Use discretion, and add an image to a form only when the image adds value to the interface.

Removing an image from a form is just as easy as adding the image in the first place. To remove the picture that you just added to your form, right-click the BackgroundImage property name and choose Reset from the shortcut menu that appears.

graphics/bookpencil.gif You must right-click the Name column of the property, not the Value column. If you right-click the value of the property, you get a different shortcut menu that doesn't have a Reset option.
Giving a Form an Icon 

The icon assigned to a form appears in the left side of the form's title bar, in the taskbar when the form is minimized, and in the iconic list of tasks when you press Alt+Tab to switch to another application. The icon often represents the application; therefore, you should assign an icon to any form a user can minimize. If you don't assign an icon to a form, C# supplies a default icon to represent it when the form is minimized. This default icon is generic and unattractive, and you should avoid it.

In the past, it was recommended that every form have a unique icon related to the form's purpose. This has proved very difficult to accomplish in large applications. As an alternative, I recommend that you set the icon of the main form in your program to the icon that you want to represent your application, and then assign that icon to other forms as they are loaded rather than assigning them at design time. If this proves to be a hassle, just assign the same icon to all your forms.

You assign an icon to a form in much the same way you assign an image to the BackgroundImage property. Add an icon to your form now by clicking the form's Icon property in the Properties window, clicking the Build button that appears, and selecting an icon file from your hard drive. After you've selected the icon, it appears in the form's title bar to the left.

Run your project by pressing F5, and then click the form's Minimize button to minimize it to the taskbar. Look at the form in the taskbar; you'll see both the form's caption and the form's icon displayed (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/05.htm#ch05fig04 Figure 5.4]).

Figure 5.4. Assigning meaningful icons to your forms makes your application easier to use.

graphics/05fig04.jpg

Stop the project now by choosing Stop Debugging from the Debug menu.

 Preventing a Form from Appearing in the Taskbar 

Being able to display an icon for a minimized form is nice, but sometimes it's necessary to prevent a form from even appearing in the taskbar. For instance, if your application has a number of palette windows that float over a main form, it's unlikely that you'd want all but your main form to appear in the taskbar. To prevent a form from appearing in the taskbar, set the form's ShowInTaskbar property to false. If the user minimizes a form with its ShowInTaskbar property set to false, the user can still get to the application by pressing Alt+Tab, even though the program can't be accessed via the taskbar; C# won't allow the application to become completely inaccessible to the user.

 Changing the Appearance and Behavior of a Form's Border 

You may have noticed while working with other Windows programs that the borders of forms can vary. Some forms have borders that you can click and drag to change the size of the form, some have fixed borders that can't be changed, and still others have no borders at all. The appearance and behavior of a form's border is controlled by its FormBorderStyle property.

The FormBorderStyle property can be set to one of the following values:

  • None
  • FixedSingle
  • Fixed3D
  • FixedDialog
  • Sizable
  • FixedToolWindow
  • SizableToolWindow

Run your project now by pressing F5, and move the mouse pointer over one of the borders of your form. This form has a sizable border, which means that the border can be resized by the user. Notice how the pointer changes from a large arrow to a line with arrows pointing on either side, indicating the direction you can stretch the border. When you move the pointer over a corner, you get a diagonal cursor that indicates you can stretch both of the sides that meet at the corner.

Stop the project now by choosing Stop Debugging from the Debug menu (or click the Close button on the form) and change the form's FormBorderStyle property to None. Your form should look like the one in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/05.htm#ch05fig05 Figure 5.5]. When you choose to not give a form a border, the title bar of the form is removed. Of course, when the title bar is gone, there is no visible title bar text, no control box, and no Minimize or Maximize buttons. Run your project by pressing F5, and notice how the form appears as it did in Form Design view�with no border or title bar. Without a border, the form cannot be resized by the user, and without a title bar, the form cannot be repositioned. Rarely is it appropriate to specify None for a form's BorderStyle, but in the event you need to do this, it's entirely possible.

Figure 5.5. You can create forms without borders.

graphics/05fig05.jpg

Stop the project (you should know how by now) and change the FormBorderStyle to FixedDialog. Press F5 to run the project again, and move the mouse pointer over a border of the form; the mouse pointer won't change, and you won't be able to stretch the borders of the form. Stop the project again and set the form's FormBorderStyle property to FixedToolWindow. This setting causes the title bar of the form to appear smaller than normal and the text to display in a smaller font (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/05.htm#ch05fig06 Figure 5.6]). In addition, the only thing displayed on the title bar besides the text is a Close button. C#'s various design windows, such as the Properties window and the toolbox, are good examples of tool windows.

Figure 5.6. A tool window is a special window whose title bar takes up the minimum space possible.

graphics/05fig06.jpg

The FormBorderStyle is a good example of how changing a single property can greatly affect the look and behavior of an object. Set the FormBorderStyle of the form back to Sizable, the default setting for new forms.

 Adding Minimize, Maximize, and Control Box Buttons to a Form 

Minimize and Maximize buttons make it easy for a user to quickly hide a form or make it fill the entire display. Adding a Minimize or Maximize button to your forms is as easy as setting a property (or two). To add a Minimize button to a form's title bar, set the form's MinimizeBox property to true. To add a Maximize button to a form, set its MaximizeBox property to true. Conversely, set the appropriate property to false to hide a button.

graphics/bookpencil.gif The form's ControlBox property must be set to true to display a Maximize and/or Minimize button on a form. When the ControlBox property of a form is set to true, a button with an X appears in the title bar at the right side, which the user can click to close the form. In addition, the form's icon is displayed in the left side of the title bar, and clicking it opens the form's System menu.

Notice that the title bar of your form shows all three buttons to the far right. From left to right, these are Minimize, Maximize, and Close. Run the project now and right-click the title bar to open the control box's menu, as shown in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/05.htm#ch05fig07 Figure 5.7]. Notice that the icon isn't visible in the form's title bar. Some FormBorderStyle settings cause the icon to be hidden. When this occurs, right-clicking the title bar causes the menu to appear as though you clicked the icon. Close the form now by either selecting Close from the menu or clicking the Close button on the far right of the title bar.

Figure 5.7. Clicking the icon of a form with a control box (or right-clicking a title bar) displays a system menu.

graphics/05fig07.jpg

Changing the MaximizeBox or MinimizeBox properties of a form enables or disables the corresponding item on the system menu in addition to the button on the toolbar. Save your project now by clicking the Save All button on the toolbar.

 Specifying the Initial Display Position of a Form 

The location on the display (monitor) where a form first appears isn't random but is controlled by the form's StartPosition property. The StartPosition property can be set to one of the values in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/05.htm#ch05table01 Table 5.1].

Value Description
Manual The Location property of the form determines where the form first appears.
CenterScreen The form appears centered in the display.
WindowsDefaultLocation The form appears in the Windows default location, which is toward the upper left of the display.
WindowsDefaultBounds The form appears in the Windows default location with its bounds (size) set to the Windows default bounds.
CenterParent The form is centered within the bounds of its parent form.
graphics/bookpencil.gif Generally, it's best to set the StartPosition property of all your forms to CenterParent, unless you have a specific reason to do otherwise. For the very first form that appears in you project, you might consider using the WindowsDefaultLocation (but I generally prefer CenterScreen).
Displaying a Form in a Normal, Maximized, or Minimized State 

Using the Size and Location properties of a form in conjunction with the StartPosition property enables you to display forms at any location and at any size. You can also force a form to appear minimized or maximized. Whether a form is maximized, minimized, or shown normally is known as the form's state, and it's determined by the WindowState property.

Look at your form's WindowState property now. New forms have their WindowState property set to Normal by default. When you run the project, as you have several times, the form displays in the same size as it appears in the form designer, at the location specified by the form's Location property. Change the WindowState property now to Minimized. Nothing happens in the Form Design view, but run your project by pressing F5 and you'll see that the form is immediately minimized to the taskbar.

Stop the project and change the WindowState property to Maximized. Again, nothing happens in the Form Design window. Press F5 to run the project and notice how the form immediately maximizes to fill the entire screen.

graphics/bookpencil.gif When a form is maximized, it fills the entire screen regardless of the current screen resolution being used in Windows.

Stop the project and change the WindowState property back to Normal. Rarely will you set a form's WindowState property at design time to Minimize, but you'll probably encounter situations in which you need to change (or determine) the WindowState at runtime. As with most properties, you can accomplish this using code. For example, the following statement would minimize a form: this.WindowState = FormWindowState. Minimized. You don't have to remember the names of the values when entering code; you'll get an IntelliSense drop-down list when you type the period.

 Changing the Mouse Pointer 

You've no doubt used a program that altered the cursor when the pointer was moved over an object. This behavior is prevalent in Web browsers, in which the cursor is changed to the shape of a pointing hand when moved over a hyperlink. Using the Cursor property, you can specify the image of the pointer displayed when the pointer is over a form (or control).

Click the Cursor property of the form in the Properties window now and a drop-down arrow appears. Click the arrow to view a list of cursors (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/05.htm#ch05fig08 Figure 5.8]). Selecting a cursor from the list causes the pointer to change to that cursor when positioned over the form. Change the Cursor property of the form to AppStarting and press F5 to run the project. Move the pointer over the form and notice that the cursor changes to the AppStarting cursor while over the form and reverts to the default cursor when moved off the form. Stop the project now and click Save All on the toolbar to save your work.

Figure 5.8. Use the Cursor property to designate the image of the pointer when it's moved over the object.

graphics/05fig08.jpg

graphics/bookpencil.gif Rarely will you want to change the cursor for a form, but you may find occasion to change the Cursor property for specific controls. Whenever you find yourself changing the default cursor for a form or control, choose a cursor that is consistent in purpose with well-known commercial applications.

Showing and Hiding Forms

[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/part03.htm#part03 Part III] of this book is devoted to programming in C#, and I've avoided going into much programming detail in this hour so that you can focus on the concepts at hand. However, knowing how to create forms does nothing for you if you don't have a way to show and hide them. Because C# can display a single form automatically only when a program starts, you have to write code to show and hide other forms.

 Showing Forms 

In C#, everything is an object, and objects are based on classes (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch17.htm#ch17 Hour 17], "Designing Objects with Classes," for information on creating classes). Because the definition of a form is a class, you have to create a new Form object using the class as a template. In [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch03.htm#ch03 Hour 3], "Understanding Objects and Collections," I discussed objects and object variables, and these principles apply to creating forms.

As discussed in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch03.htm#ch03 Hour 3], the process of creating an object from a class (template) is called instantiation. The syntax you'll use most often to instantiate a form is the following:

{ formclassname } {objectvariable} = new {formclassname()} ;

The parts of this declaration are as follows:

  • formclassname the name of the class that defines the form.
  • objectvariable This is the name for the form that you will use in code.
  • The keyword new Indicates that you want to instantiate a new object for the variable.

Last, you specify the name of the class used to derive the object�your form class. If you have a form class named fclsLoginDialog, for example, you could create a new Form object using the following code:

fclsLoginDialog frmLoginDialog = new fclsLoginDialog();

Thereafter, for as long as the object variable remains in scope (scope is discussed in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch12.htm#ch12 Hour 12], "Using Constants, Data Types, Variables, and Arrays"), you can manipulate the Form object using the variable. For instance, to display the form, you call the Show method of the form or set the Visible property of the form to true using code such as this:

frmLoginDialog.Show();

or

frmLoginDialog.Visible = true;

The easiest way to get the hang of this is to actually do it. To begin, choose Add Windows Form from the Project menu to display the Add New Item dialog box. Change the name of the form to fclsMyNewForm.cs (as shown in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/05.htm#ch05fig09 Figure 5.9]), and click Open to create the new form.

Figure 5.9. When you change the default name of a form, remember to leave the .cs extension.

graphics/05fig09.jpg

Your project now has two forms, as you can see by viewing the Solution Explorer window. The new form is displayed in the form designer, but right now you need to work with the main form. At the top of the main design area is a set of tabs. Currently, the tab fclsMyNewForm.cs [Design] is selected. Click the tab titled Form1.cs [Design] to show the designer for the first form.

graphics/bookpencil.gif Notice how the designer uses the filename rather than the object name on the tabs. You could right-click Form1.cs in the Solutions Explorer window and choose Rename to change the name of the file and therefore the name that appears on the tabs. You should actually do this in all your projects for the default forms. However, I haven't done this throughout the book because it adds yet another step to each example, and I don't want to complicate things too much.

Add a new button to your original form by double-clicking the Button item on the toolbox (be careful not to add the button to the new form by mistake). Set the button's properties as follows:

Property Value
Name btnShowForm
Location 112,112
Text Show Form

Double-click the button to access its Click event (double-clicking a control is a shortcut for accessing its default event) and enter the following code:

fclsMyNewForm frmTest = new fclsMyNewForm();
frmTest.Show();

The first statement creates a new object variable and instantiates an instance of the fclsMyNewForm form. The second statement uses the object variable, now holding a reference to a Form object, to display the form. Press F5 to run the project and click the button. (If the button doesn't appear on the form, you may have accidentally added it to the wrong form). When you click the button, a new instance of the second form is created and displayed. Move this form and click the button again. Each time you click the button, a new form is created. Stop the project now and click Save All on the toolbar.

 Understanding Form Modality 

You can present two types of forms to the user: modal and nonmodal forms. The modality of a form is determined by how you show the form rather than by how you create the form (both modal and nonmodal forms are created the same way).

A nonmodal window is a window that doesn't cause other windows to be disabled. The forms you created in this example are nonmodal, which is why you were able to continue clicking the button on the first form even though the second form was displayed. Another example of a nonmodal window is the Find and Replace window in Word (and in C#, as well). When the Find and Replace window is visible, the user can still access other windows.

When a form is displayed as a modal form, on the other hand, all other forms in the same application become disabled until the modal form is closed; the other forms won't accept any keyboard or mouse input. The user is forced to deal only with the modal form. When the modal form is closed, the user is free to work with other visible forms within the program. Modal forms are most often used to create dialog boxes in which the user works with a specific set of data and controls before moving on. For instance, the Print dialog box of Microsoft Word is a modal dialog box. When the Print dialog box is displayed, the user cannot work with the document on the main Word window until the Print dialog box is closed. Most secondary windows in any given program are modal windows.

graphics/bookpencil.gif You can display one modal form from another modal form, but you cannot display a nonmodal form from a modal form.

To show a form as a modal form, you call the form's ShowDialog method rather than its Show method. Change the code in your button's Click event to read:

fclsMyNewForm frmTest = new fclsMyNewForm();
frmTest.ShowDialog();

When your code looks like this, press F5 to run the project. Click the button to create an instance of the second form. Then, move the second form away from the first window and try to click the button again. You can't�because you've created a modal form. Close the modal form now by clicking the Close button in the title bar. Now, the first form is enabled again and you can click the button once more. When you are done testing this, stop the running project.

graphics/bookpencil.gif You can test to see whether a form has been shown modally by testing the form's Modal property.
Unloading Forms 

After a form has served its purpose, you'll want it to go away. However, "go away" can mean one of two things. First, you can make a form disappear without closing it or freeing its resources (this is called hiding). To do so, set its Visible property to false. This hides the visual part of the form, but the form still resides in memory and can still be manipulated by code. In addition, all the variables and controls of the form retain their values when a form is hidden, so that if the form is displayed again, the form looks the same as it did when its Visible property was set to false.

Second, you can completely close a form and release the resources it consumes. You should close a form when it's no longer needed, so Windows can reclaim all resources used by the form. To do so, you invoke the Close method of the form like this:

this.Close();

In [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch03.htm#ch03 Hour 3], you learned how this is used to reference the current Form object. Because this represents the current Form object, you can manipulate properties and call methods of the current form using this. (this.Visible = false, and so forth).

The Close method tells C# to not simply hide the form, but to destroy it completely. If variables in other forms are holding a reference to the form you close, their references will be set to null and will no longer point to a valid Form object (refer to [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch12.htm#ch12 Hour 12] for information on null).

Select the fclsMyNewForm.cs [Design] tab to display the form designer for the second form, add a new button to the form, and set the button's properties as follows:

Property Value
Name btnCloseMe
Location 112,112
Text Close Me

Double-click the button to access its Click event and then enter the following statement:

this.Close();

Next, run the project by pressing F5. Click the Show Form button to display the second form, and then click the second form's button. The form will disappear. Again, the form isn't just hidden; the form instance is unloaded from memory and no longer exists. You can create a new one by single-clicking the Show Form button on the first form. When you're finished, stop the running project and save your work.

Summary 

In this hour, you've learned the basics of creating forms. You've learned how to add them to your project, how to set basic appearance properties, and how to show and hide them using C# code. In the next hour, you'll learn more advanced functionality for working with forms. After you've mastered the material in this hour as well as in the next hour, you'll be ready to dig into C#'s controls; that's where the fun of building an interface really begins!

Q&A
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/05.htm#qad1e16659 Q1:] How many form properties should I define at design time vs. runtime?
A1: You should set all properties that you can at design time. First, it'll be easier to work with the form because you can see exactly what the user will see. Also, debugging is easier because there's less code.
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/05.htm#qad1e16669 Q2:] Should I let the user minimize and maximize all forms?
A2: Probably not. First, there's no point in letting a form be maximized if you haven't anchored and aligned controls so that they adjust their appearance when the form is resized. In fact, if a form's contents don't change when a form is resized (including maximized), the form should not have a sizable border or a Maximize button.

Workshop

The Workshop is designed to help you anticipate possible questions, review what you've learned, and get you thinking about how to put your knowledge into practice. The answers to the quiz are in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01.htm#app01 Appendix A], "Answers to Quizzes/Exercises."

 Quiz
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec5.htm#ch05ans01 1:] True or False: The text displayed in the form's title bar is determined by the value in the TitleBarText property.
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec5.htm#ch05ans02 2:] The named color Control is what kind of color?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec5.htm#ch05ans03 3:] In what three places are a form's icon displayed?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec5.htm#ch05ans04 4:] A window with a smaller than normal title bar is called what?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec5.htm#ch05ans05 5:] For a Minimize or Maximize button to be visible on a form, what other element must be visible?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec5.htm#ch05ans06 6:] What, in general, is the best value to use for the StartPosition property of a form?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec5.htm#ch05ans07 7:] To maximize, minimize, or restore a form in code, you set what property?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec5.htm#ch05ans08 8:] True or False: To display a form, you must create a variable in code.
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec5.htm#ch05ans09 9:] What property do you set to make a hidden form appear?
Exercises
  1. Create a semitransparent form with a picture in its background. (Hint: Change the form's Opaque property.) Does the image become transparent? Add some controls to the form. Does the image appear behind or in front of the controls? (Hint: To create a transparent form, set the form's Opacity to something other than 100%�try 50%.)
  2. Create a Windows Application with three forms. Give the startup form two buttons. Make the other two forms tool windows, and make one button display one tool window and the other button display the second tool window.