Jump to content

User:Foxall/1

Ka Wiktionary

Hour 1. A C# Programming Tour

[wax ka badal]

Learning a new programming language can be intimidating. If you've never programmed before, the act of typing seemingly cryptic text to produce sleek and powerful applications probably seems like a black art, and you may wonder how you'll ever learn everything you need to know. The answer is, of course, one step at a time. The first step to learning a language is the same as that of any other activity�building confidence. Programming is part art and part science. Although it may seem like magic, it's more akin to illusion; after you know how things work, a lot of the mysticism goes away, freeing you to focus on the mechanics necessary to produce the desired result.

In this hour, you'll complete a quick tour that takes you step-by-step through creating a complete, albeit small, C# program. I've yet to see a "Hello World" program that's the least bit helpful (they usually do nothing more than print "hello world" to the screen�oh, fun). So instead, you'll create a picture-viewer application that lets you view Windows bitmaps and icons on your computer. You'll learn how to let a user browse for a file and how to display a selected picture file on the screen, both of which are skills that will come in handy in later applications that you create. Creating large, commercial solutions is accomplished by way of a series of small steps. After you've finished creating this small project, you'll have an overall feel for the development process.

The highlights of this hour include the following:

  • Building a simple, yet functional, C# application
  • Letting a user browse a hard drive
  • Displaying a picture from a file on disk
  • Getting familiar with some programming lingo
  • Learning about the Visual Studio�C# IDE

I hope that by the end of this hour, you'll realize just how much fun it is to program using C#.

Starting C#

[wax ka badal]

You must become familiar with a few terms before you begin to create programs in C#:

  • Distributable Component The final, compiled version of a project. Components can be distributed to other people and other computers and do not require C# to run (although the .NET Framework is required, which you'll learn about in coming hours). Distributable components are also called programs. In [Hour 22], "Deploying a Solution," you'll learn how to distribute the Picture Viewer program that you're about to build to other computers.
  • Project A collection of files that can be compiled to create a distributable component (program). There are many types of projects, and complex applications may consist of many projects, such as a Windows Application project and support DLL projects.
  • Solution A collection of projects and files that compose an application or component.
New term
C# is a complete development environment; every tool you'll need to create your C# projects is accessed from within Visual Studio. The Visual Studio-C# environment is called the IDE, short for Integrated Development Environment, and it is the design framework in which you build applications. To work with C# projects, you must first start the Visual Studio IDE.


Start the C# IDE now by choosing Microsoft Visual Studio .NET from within the Microsoft Visual Studio .NET folder on your Start menu.




Creating a New Project

[wax ka badal]

When you first start Visual Studio .NET, you're shown the Visual Studio Start Page tab within the IDE. Using this page, you can open projects created previously or create new ones (see [Figure 1.1]). For this quick tour, you're going to create a new Windows application, so click New Project to display the New Project dialog box shown in [Figure 1.2].

Figure 1.1. You can open existing projects or create new projects from the Visual Studio Start page.

Figure 1.2. The New Project dialog box allows you to create many types of .NET projects.

Book - Pencil
If you don't see the Visual Studio Start page, chances are that you've changed the default settings. [Hour 2], "Navigating C#," shows you how to change them back. For now, be aware that you can create a new project from the File menu in addition to using the techniques described in this hour.


You can create many types of projects with C#, as well as with the other supported languages of the .NET platform. The New Project dialog box is used to specify the type of C# project you want to create. If the Visual C# Projects folder isn't selected, click it to display the C# project types and then make sure the Windows Application icon is selected (if it's not, click it once to select it). At the bottom of the New Project dialog box is a Name text box, in which you specify the name of the project you're creating; in the Location text box, you can enter the location in which to save the project files.

Bulb
You should always set these values to something meaningful before creating a project, or you'll have more work to do later if you want to move or rename the project.


Type Picture Viewer into the Name text box to name your project. There's no need to change the location where the project files are to be saved at this time, so go ahead and create the new Windows Application project by clicking OK. C# creates the new project, complete with one form (design window) for you to begin building the interface for your application (see [Figure 1.3]).

Figure 1.3. New Windows applications start with a blank form; the fun is just beginning!

Your C# environment may look different from that shown in the figures of this hour, depending on the edition of C# you're using, whether you've already played with C#, and other factors such as the resolution of your monitor. All the elements discussed in this hour, however, exist in all editions of C#. (If your IDE doesn't have a window displayed that is shown in a figure, use the View menu to display the window.)

Book - Pencil
To create a program that can be run on another computer, you start by creating a project, and then you compile the project into a component, such as an executable (a program a user can run) or a DLL (a component that can be used by other programs and components). The compilation process is discussed in detail in [Hour 22], "Deploying a Solution." The important thing to note at this time is that when you hear someone refer to creating or writing a program, just as you are creating the Picture Viewer program now, they're referring to the completion of all steps up to and including compiling the project to a distributable file.




Understanding the C# Environment

[wax ka badal]

The first time you run C#, you'll notice that the IDE contains a lot of windows, such as the Properties window on the right, which is used to view and set properties of objects. In addition to these windows, the IDE contains a lot of tabs, such as the Toolbox tab on the left edge of the IDE (refer tFigure 1.3]). Clicking a tab displays an associated window. Try this now: click the Toolbox tab to display the Toolbox window. You can also hover the mouse over a tab for a few seconds to display the window. To hide the window, simply move the mouse off the window. To close the window completely, click the Close (X) button in the window's title bar.

You can adjust the size and position of any of these windows, and you can even hide and show them at will. You'll learn how to customize your design environment in [Hour 2], "Navigating C#."

Bulb
Unless specifically instructed to do so, do not double-click anything in the C# design environment. Double-clicking most objects produces an entirely different outcome than single-clicking does. If you mistakenly double-click an object on a form, a code window is displayed. At the top of the code window is a set of tabs: one for the form design and one for the code. Click the tab for the form design to hide the code window and return to the form.


The Properties window at the right side of the design environment is perhaps the most important window, and it's the one you'll use most often. If your computer's display is set for 640x480, you can probably see only a few properties at this time. This makes it difficult to view and set properties as you create projects. I highly recommend that you don't attempt development with Visual Studio at a resolution below 800x600. Personally, I prefer 1024x768 because it offers plenty of work space. To change your display settings, right-click your desktop and select Properties.




Changing the Characteristics of Objects

[wax ka badal]

Almost everything you work with in C# is an object. Forms, for instance, are objects, as are all the items you can put on a form to build an interface, such as list boxes and buttons. There are many types of objects ([Hour 3], "Understanding Objects and Collections," discusses objects in detail). Objects, in turn, are classified by type. For instance, a form is a Form object, whereas items you can place on a form are called Control objects, or controls. Some objects don't have a physical appearance, but exist only in code. You'll learn about these kinds of objects in later hours.

New term
Every object, regardless of whether it has a physical appearance, has a distinct set of attributes known as properties. You have certain properties about you, such as your height and hair color, and C# objects have properties as well, such as Height and BackColor. Properties define the characteristics of an object. When you create a new object, the first thing you need to do is set its properties so that the object appears and behaves in the way you desire. To display the properties of an object, click the object in its designer. Click the form now to ensure that its properties are displayed in the Properties window.




Naming Objects

[wax ka badal]

The property you should set first for any new object is the Name property. Press F4 to display the Properties window (if it's not already visible), and notice the Name given to your default form (the first property listed in the Properties window)�Form1. When you first create an object, C# gives the object a unique, generic name based on the object's type. Although these names are functional, they aren't very descriptive. For instance, C# named your form Form1, but it's common to have dozens of forms in a project, and it would be extremely difficult to manage a complicated project if all forms were distinguishable only by a number (Form2, Form3, and so forth).

Book - Pencil
In actuality, what you're creating is a form class, or template, that will be used to create and show forms at runtime. For the purpose of this quick tour, I simply refer to it as a form. See [Hour 5], "Building Forms�Part I," for more information.


To better manage your forms, you should give each one a descriptive name. C# gives you the chance to name new forms as they're created. Because C# created this default form for you, you didn't get a chance to name it, so you must change both the filename and name of the form. Change the name of the form now by clicking the Name property and changing the text from Form1 to fclsViewer. Notice that this did not change the filename of the form as it is displayed in the Solution Explorer window. Change the filename now by right-clicking Form1.cs in the Solution Explorer window, choosing Rename from the context menu, and changing the text from Form1.cs to fclsViewer.cs. In future examples, I won't have you change the filename each time because you'll have enough steps to accomplish as it is. I do recommend, however, that you always change your filenames to something meaningful in your 'real' projects.

Book - Pencil
I use the fcls prefix here to denote that the file is a form class. There are different types of classes, so using a prefix helps differentiate the classes in code. You're not required by C# to use object prefixes, but I highly recommend that you do so. In [Hour 12], "Using Constants, Data Types, Variables, and Arrays," you'll learn the benefits of using a naming convention as well as the standard prefixes for many .NET objects.




Setting the Text Property of the Form

[wax ka badal]

Notice that the text that appears in the form's title bar says Form1. This is because C# sets the form's title bar text to the name of the form when it is first created, but doesn't change it when you change the name of the form. The text in the title bar is determined by the value of the Text property of the form. Click the form once more so that its properties appear in the Properties window. Use the scrollbar in the Properties window to locate the Text property in the Properties window and then change the text to Picture Viewer.




Giving the Form an Icon

[wax ka badal]

Everyone who has used Windows is familiar with icons, which are the little pictures used to represent programs. Icons most commonly appear in the Start menu next to the name of their respective programs. In C#, you not only have control over the icon of your program file, you can also give every form in your program a unique icon if you want to.

Book - Pencil
The instructions that follow assume you have access to the source files for the examples in this book. They are available at www.samspublishing.com/detail_sams.cfm?item=0672320800. You don't have to use the icon I've provided for this example; you can use any icon of your choice. If you don't have an icon available, you can skip this section without affecting the outcome of the example.


To give the form an icon, follow these steps:

  1. In the Properties window, click the Icon property to select it.
  2. When you click the Icon property, a small button with three dots appears to the right of the property. Click this button.
  3. To locate the HourOne.ico file or another ico file of your choice, use the Open dialog box that appears. When you've found the icon, double-click it, or click it once to select it and then click Open.

After you've selected the icon, it appears in the Icon property along with the word (Icon). A small version of the icon appears in the upper-left corner of the form, as well. Whenever this form is minimized, this is the icon that's displayed on the Windows taskbar. (Note: This doesn't change the icon for the project as a whole. In [Hour 22], you'll learn how to assign an icon to your distributable file.)




Changing the Size of the Form

[wax ka badal]

Next, you're going to change the Width and Height properties of the form. The Width and Height values are shown collectively under the Size property; Width appears to the left of the comma, Height to the right. You can change the Width or Height by changing the corresponding number in the Size property. Both values represent the number of pixels of the dimension. To display and adjust the Width and Height properties separately, click the small plus sign (+) next to the Size property (see [Figure 1.4]).

Figure 1.4. Some properties can be expanded to show more specific properties.

Change the Width property to 400 and the Height to 325. To commit a property change, press Tab or click a different property or window. Your screen should now look like the one in [Figure 1.5].

Figure 1.5. A change in the Properties window is reflected as soon as the change is committed.

When you first created this project, C# saved a copy of the source files in their initial state. The changes you've made so far exist only in memory; if you were to turn your computer off at this time (don't do this), you would lose any and all work up to this point. You should get into the habit of saving your work frequently. Save the project now by choosing Save All from the File menu or by clicking the Save All button on the toolbar (it has a picture of stacked disks on it).




Adding Controls to a Form

[wax ka badal]
New term
Now that your form has its properties set, you need to add objects to the form to produce a user interface. Objects that can be placed on a form are called controls. Some controls have a visible interface with which a user can interact, whereas others are always invisible to the user. You'll use controls of both types in this example. On the left side of the screen is a tab titled Toolbox. Click the Toolbox tab now to display the Toolbox window shown in [Figure 1.6]. The toolbox contains all the controls available in the project, such as labels and text boxes.


Figure 1.6. The toolbox is used to select controls to build a user interface.

Bulb
You can add a control to a form in three ways, and [Hour 5] explains them in detail. In this hour, you'll use the technique of double-clicking a tool in the toolbox.


The toolbox closes itself soon after you've added a control to a form and the pointer is no longer over the toolbox. To make the toolbox stay visible, click the little picture of a pushpin located in the toolbox's title bar.

Book - Pencil
Refer to [Hour 2], "Navigating C#," for more information on customizing the design environment.


Your Picture Viewer interface will consist of the following controls:

  • Two Button controls
  • A PictureBox control
  • An OpenFileDialog control





Designing an Interface

[wax ka badal]

It's generally best to design the user interface of a form and then add the code behind the interface that makes the form functional. The user interface for your Picture Viewer program will consist of a View Picture button, a Close button, and a PictureBox in which to display a picture.

Adding a Visible Control to a Form

[wax ka badal]

Start by adding a Button control to the form. Do this by double-clicking the Button item in the toolbox. C# then creates a new button and places it in the upper-left corner of the form (see [Figure 1.7]).

Figure 1.7. When you double-click a control in the toolbox, the control is added to the upper-left corner of the form.

Using the Properties window, set the button's properties as follows (note that you may want to change the Properties list to alphabetical, if it is not already, to make it easier to find these properties by name):

Property Value
Name btnSelectPicture
Text Select Picture
Location 301,10 (Note: 301 is the x coordinate, 10 is the y coordinate.)
Size 85,23

You're now going to create a button that the user can click to close the Picture Viewer program. Rather than adding a new button to the form, you're going to create a copy of the button you've already defined. To do this, right-click the button on the form and choose Copy from its shortcut menu. Next, right-click anywhere on the form and choose Paste from the form's shortcut menu. The new button appears over the button you copied, and it is selected by default. Change the properties of the new button as follows:

Property Value
Name btnQuit
Text Quit
Location 301,40

The last control you need to add to the form is a PictureBox control. A PictureBox has many capabilities, but its primary purpose is to show pictures�which is precisely what you'll use it for in this example. Add a new PictureBox control to the form and set its properties as follows:

Property Value
Name picShowPicture
BorderStle FixedSingle
Location 8,8
Size 282, 275

After you've made these property changes, your form will look like the one in [Figure 1.8]. Click the Save All button on the toolbar to save your work.

Figure 1.8. An application's interface doesn't have to be complex to be useful.





Adding an Invisible Control to a Form

[wax ka badal]
New term
So far, all the controls that you've used sit on a form and have a physical appearance. However, not all controls have a physical appearance. Such controls, referred to as invisible-at-runtime controls, aren't designed for user interactivity, but they're designed to give you, the programmer, functionality beyond the standard features of C#.


To allow the user to select a picture to display, you need to give her the capability to locate a file on her hard drive. You've probably noticed in the past that whenever you choose to open a file from within any Windows application, the dialog box displayed is almost always the same. It doesn't make any sense to force each and every developer to write the code necessary to perform standard file operations. Instead, Microsoft has exposed the functionality via a control that you can use in your project. This control is called the OpenFileDialog control, and it will save you dozens of hours that you would otherwise spend trying to duplicate common functionality.

Book - Pencil
Other controls besides the OpenFileDialog control give you file functionality. For example, the SaveFileDialog control provides features for enabling the user to save a file.


Scroll the toolbox until you can see the OpenFileDialog control, and then double-click it to add it to your form. (You may have to scroll the toolbox, which is done by clicking the up arrow toward the top of the window or the down arrow toward the bottom.) Note that the control isn't placed on the form, but it appears in a special area below the form (see [Figure 1.9]). This happens because the OpenFileDialog control has no interface to display to a user. It does have an interface, a dialog box that you can display as necessary, but it has nothing to display directly on a form.

Figure 1.9. Controls that have no interface appear below the form designer.

Select the OpenFileDialog control and change its properties as follows:

Property Value
Name ofdSelectPicture
Filter *.BMP|JPEG Files|*.JPG
Title Select Picture

The Filter property determines the filtering of the control. The text that appears before the pipe symbol (|) is the descriptive text of the file type, whereas the text after the pipe symbol is the pattern to use to filter files; you can specify more than one filter type. Text entered into the Title property appears in the title bar of the Open File dialog box.





Coding an Interface

[wax ka badal]

The graphical interface for your Picture Viewer program is now complete, so click the pushpin in the title bar of the toolbox to close it. Now, you have to write code for the program to be capable of performing actions. C# is an event-driven language, which means that code is executed in response to events. These events may come from users, such as a user clicking a button, or from Windows itself (see [Hour 4], "Understanding Events," for a complete explanation of events). Currently, your application looks nice but it won't do a darn thing. The user can click the Select Picture button, for example, until the cows come home, but nothing will happen because you haven't told the program what to do when the user clicks the button.

You're going to write code to accomplish two tasks. First, you're going to write code that lets the user browse his or her hard drives to locate and select a picture file and then display the file in the picture box (this sounds a lot harder than it is). Second, you're going to add code to the Quit button that shuts down the program when the user clicks the button.

Letting a User Browse for a File

[wax ka badal]

The first bit of code you're going to write will allow the user to browse his or her hard drives, select a file, and then show the selected picture in the PictureBox control. This code will execute when the user clicks the Select Picture button; therefore, it's added to the Click event of that button (you'll learn all about events in later hours). When you double-click a control on a form in Design view, the default event for that control is created and displayed in a code window. The default event for a Button control is its Click event, which makes sense because clicking a button is its most common purpose. Double-click the Select Picture button now to access its Click event in the code window (see [Figure 1.10]).

Figure 1.10. You will write all code in a window such as this.

New term
When you access an event, C# builds an event handler, which is essentially a template procedure in which you add the code that executes when the event is fired. The cursor is already placed within the code procedure, so all you have to do is add code. You will also notice that the open and closing braces are preset for your new event procedure. The braces, in this case, define the beginning and end of your procedure. You will soon see that C# requires many open and closing braces({ } ). By the time you're done with this book, you'll be madly clicking away as you write your own code to make your applications do exactly what you want them to do�well, most of the time. For now, just enter the code as I present it here.


It's very important that you get in the habit of commenting your code, so the first line you're going to enter is a comment. Beginning a statement with the characters // designates the statement as a comment; the compiler won't do anything with the statement, so you can enter whatever text you want after the double slashes. Type the following statement exactly as it appears and press the Enter key at the end of the line.

Book - Pencil
For more information on creating good comments, see [Hour 16], "Debugging Your Code."


// Show the open file dialog box.

The next statement you'll enter triggers a method of the OpenFileDialog control that you added to the form. You'll learn all about methods in [Hour 3], "Understanding Objects and Collections." For now, think of a method as a mechanism to make a control take action. The ShowDialog method tells the control to show its Open dialog box and let the user select a file. The ShowDialog method returns a value that indicates its success or failure, which we are then comparing to a predefined result (DialogResult.OK). Don't worry too much about what is happening here, because you'll be learning the details of this in later hours. In a nutshell, the ShowDialog method is called to let a user browse for a file, and if the user selects a file, more code gets executed. Of course, there is a lot more to using the OpenFileDialog control than I present in this basic example, but this simple statement gets the job done. Enter the following if statement followed by an open brace:

if (ofdSelectPicture.ShowDialog() == DialogResult.OK)
 {
Book - Pencil
Open and closing braces are necessary for this if statement because they denote that multiple lines will be part of this construct.


Time for another comment. Enter this statement and remember to press Enter at the end of each code line.

// Load the picture into the picture box.
Bulb
Don't worry about indenting the code by pressing the Tab key or using spaces. C# .NET automatically indents code for you.


You're now going to enter the next line of code. This statement, which appears within the if construct, is the line of code that actually displays the picture in the picture box. (If you're itching to know more about graphics, take a look at [Hour 10], "Drawing and Printing.")

Enter the following statement:

picShowPicture.Image = Image.FromFile(ofdSelectPicture.FileName);

In addition to displaying the selected picture, your program is going to display the path and filename of the picture in the title bar. When you first created the form, you changed the Text property of the form using the Properties window. To create dynamic applications, properties need to be constantly adjusted at runtime, and this is done using code. Enter the following three lines of code:

// Show the name of the file in the form's caption.
this.Text = String.Concat("Picture Viewer (" + ofdSelectPicture.FileName + ")");
}
Book - Pencil
C# is case sensitive! You must enter all code using the same case as shown in the text.


Checking Your Program Entry Point

[wax ka badal]

All C# programs must contain an entry point. The Main() method is the entry point. In this sample you need to change the reference from Form1 to fclsViewer (this is necessary because we renamed the form earlier) . This statement will invoke the constructor on the form. C++ programmers will be familiar with the Main() entry point method, but they should take notice of the capitalization of Main. We will talk a bit more about the program entry point later in the book.

To update the entry point in this sample, press Ctrl+F to open the Find window, enter Form1, and click Find Next. Close the Find window and replace the text Form1 with fclsViewer. The updated statement should now read:

Application.Run(new fclsViewer());

After you've entered all the code, your editor should look like that shown in [Figure 1.11].

Figure 1.11. Make sure your code exactly matches the code shown here.

Terminating a Program Using Code

[wax ka badal]

The last bit of code you'll write will terminate the application when the user clicks the Quit button. To do this, you'll need to access the Click event handler of the btnQuit button. At the top of the code window are two tabs. The current tab has the text fclsViewer.cs. Next to this is a tab that contains the text fclsViewer.cs [Design]. Click this tab now to switch from Code view to the form designer. If you receive an error when you click the tab, the code you entered is incorrect, and you need to edit it to make it the same as I've presented it. After the form designer is displayed, double-click the Quit button to access its Click event.

Enter the following code in the Quit button's Click event handler:

this.Close();
Book - Pencil
The Close statement closes the current form. When the last loaded form in a program is closed, the application shuts itself down�completely. As you build more robust applications, you'll probably want to execute all kinds of clean-up routines before terminating your application, but for this example, closing the form is all you need to do.


Running a Project

[wax ka badal]

Your application is now complete. Click the Save All button (it looks like a stack of disks) on the toolbar, and then run your program by pressing F5. You can also run the program by clicking the button on the toolbar that looks like a right-facing triangle and resembles the Play button on a VCR (this button is also found on the Debug menu, and it is called Start). However, learning the keyboard shortcuts will make your development process move along faster. When you run the program, the C# interface changes, and the form you've designed appears floating over the design environment (see [Figure 1.12]).

Figure 1.12. When in Run mode, your program executes the same as it would for an end user.



You're now running your program as though it were a standalone application running on another user's machine; what you see is exactly what someone else would see if they ran the program (without the C# design environment in the background, of course). Click the Select Picture button to display the Select Picture dialog box (see [Figure 1.13]). Use the dialog box to locate a picture file. When you've found a file, double-click it, or click once to select it and then click Open. The selected picture is then displayed in the PictureBox control, as shown in [Figure 1.14].

Figure 1.13. The OpenFileDialog control handles all the details of browsing for files. Cool, huh?

Figure 1.14. C# makes it easy to display pictures with very little work.



Summary

[wax ka badal]

When you're done playing with the program, click the Quit button and then save your project by clicking Save All on the C# toolbar.

That's it! You've just created a bona fide C# program. You've used the toolbox to build an interface with which users can interact with your program, and you've written code in strategic event handlers to empower your program to do things. These are the basics of application development in C#. Even the most complicated programs are built using this basic approach; you build the interface and add code to make the application do things. Of course, writing code to do things exactly the way you want things done is where the process can get complicated, but you're on your way.

If you take a close look at the organization of the hours in this book, you'll see that I start out by teaching you the C# environment. I then move on to building an interface, and later I teach you all about writing code. This organization is deliberate. You might be a little anxious to jump in and start writing serious code, but writing code is only part of the equation. As you progress through the hours, you'll be building a solid foundation of development skills.

Soon, you'll pay no attention to the man behind the curtain�you'll be that man (or woman)!





Q1: Can I show bitmaps of file types other than BMP and JPG?
A1: Yes. The PictureBox supports the display of images with the extensions BMP, JPG, ICO, EMF, WMF, and GIF. The PictureBox can even save images to a file.
Q2: Is it possible to show pictures in other controls?
A2: The PictureBox is the control to use when you are just displaying images. However, many other controls allow you to display pictures as part of the control. For instance, you can display an image on a Button control by setting the button's Image property to a valid picture.

Workshop

[wax ka badal]

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 [Appendix A],"Answers to Quizzes/Exercises."


1 What type of C# project creates a standard Windows program?
2 What window is used to change the attributes (location, size, and so on) of a form or control?
3 How do you access the default event (code) of a control?
4 What property of a PictureBox do you set to display an image?
5 What is the default event for a Button control?

Exercise

[wax ka badal]
  1. Change your Picture Viewer program so that the user can also locate and select GIF files. (Hint: Change the Filter property of the OpenFileDialog control.)
  2. Alter the form in your Picture Viewer project so that the buttons are side by side in the lower-right corner of the form, rather than vertically aligned in the upper-right corner.



Hour 2. Navigating C#

[wax ka badal]

The key to expanding your knowledge of C# is to become as comfortable as possible�as quickly as possible�with the C# design environment. Just as a carpenter doesn't think much about hammering a nail into a piece of wood, performing actions such as saving projects, creating new forms, and setting object properties should become second nature to you. The more comfortable you are with the tools of C#, the more you can focus your energies on what you're creating with the tools.

In this hour, you'll learn how to customize your design environment. You'll learn how to move, dock, float, hide, and show design windows, as well as how to customize menus and toolbars; you'll even create a new toolbar from scratch. After you've gotten acquainted with the environment, I'll teach you about projects and the files that they're made of (taking you beyond what was briefly discussed in [Hour 1], "A C# Programming Tour"), and I'll introduce you to the design windows with which you'll work most frequently. Finally, I'll show you how to get help when you're stuck.

The highlights of this hour include the following:

  • Navigating C#
  • Using the Visual Studio .NET Start Page to open and create projects
  • Showing, hiding, docking, and floating design windows
  • Customizing menus and toolbars
  • Adding controls to a form using the toolbox
  • Viewing and changing object attributes using the Properties window
  • Working with the files that make up a project
  • How to get help



Using the Visual Studio .NET Start Page

[wax ka badal]

By default, the Visual Studio Start Page shown in [Figure 2.1] is the first thing you see when you start C# (if C# isn't running, start it now). The Visual Studio Start Page is a gateway for performing tasks with C#. From this page, you can open previously edited projects, create new projects, edit your user profile, and browse information provided by Microsoft.

Figure 2.1. The Visual Studio Start Page is the default starting point for all Visual Studio programming languages, including C#.

From this page, you can have C# load the last solution you edited, show the Open Project dialog box, show the New Project dialog box, or show an empty design environment. To view or edit the startup options, choose Options from the Tools menu to display the Options dialog box shown in [Figure 2.2]. By default, the General section of the Environment folder is selected, which happens to contain the At Startup option.

Figure 2.2. Use the At Startup setting to control the first thing you see when C# starts.

Book - Pencil
If the Visual Studio Start Page doesn't appear when you start C#, check the settings on the Options form; you may need to change At Startup to Show Start Page.


Creating New Projects

[wax ka badal]

To create new projects, click New Project on the Visual Studio Start Page. This shows the New Project dialog box shown in [Figure 2.3]. The Project Types list varies from machine to machine, depending on which products of the Visual Studio .NET family are installed. Of course, we're interested only in the C# Project types in this book.

Figure 2.3. Use the New Project dialog box to create C# projects from scratch.

Book - Pencil
You can create many types of projects with C#, but this book focuses mostly on creating Windows Applications, perhaps the most common of the project types. You will learn about some of the other project types as well, but when you're told to create a new project, make sure the Windows Application template is selected unless you're told otherwise.


When you create a new project, be sure to enter a name for it in the Name text box before clicking OK or double-clicking a project type icon. This ensures that the project is created with the proper path and filenames, eliminating work you would otherwise have to do to change these values later. After you specify a name, you can create the new project either by double-clicking the project type template icon or by clicking an icon once to select it and then clicking OK. After you've performed either of these actions, the New Project dialog box closes and a new project of the selected type is created.

By default, Visual Studio saves all your projects in subfolders of your My Documents folder. The hierarchy used by C# is

\My Documents\Visual Studio Projects\<Project Name> 

Notice how the name you give your project is used as its folder name. This makes it easy to find the folders and files for any given project and is one reason that you should always give your projects descriptive names. You can use a path other than the default by specifying a specific path on the New Project dialog box, although you probably won't often need to do so.

Book - Pencil
You can create a new project at any time (not just when starting C#) by opening the New submenu on the File menu and choosing Project.


Opening an Existing Project

[wax ka badal]

Over time, you'll open more projects than you create. There are essentially two ways to open projects from the Visual Studio Start Page. If it's one you've recently opened, the project name will appear in a list within a rectangle in the middle of the Start Page (refer to [Figure 2.1]). Because the name displayed for the project is the one given when it was created, this is yet another reason to give your projects descriptive names. Clicking a project name opens the project. I'd venture to guess that you'll use this technique 95% of the time. To open a project for the first time (such as when opening sample projects), click Open Project on the Visual Studio Start Page. Clicking this link displays a standard dialog box that you can use to locate and select a project file.

Book - Pencil
As with creating new projects, you can open an existing project at any time, not just when starting C#, by selecting File, Open.



[wax ka badal]

C# lets you customize many of its interface elements, such as windows and toolbars, enabling you to be more efficient in the work that you do. Create a new Windows Application now (use the New Project dialog box or select File, New) so that you can see and manipulate the design environment. Name this project Environment Tutorial. (This exercise won't create anything reusable, but it will help you learn how to navigate the design environment.) Your screen should look like the one shown in [Figure 2.4].

Figure 2.4. This is pretty much how the IDE appears when you first install C#.

Book - Pencil
Your screen may not look exactly like that shown in [Figure 2.4], but it'll be close. For example, the Output window won't be visible unless you've built a project. If you completed [Hour 1], the window will be visible. By the time you've finished this hour, you'll be able to change the appearance of the design environment to match this figure�or to any configuration you prefer.


Working with Design Windows

[wax ka badal]

Design windows, such as the Properties and Solution Explorer windows shown in [Figure 2.4], provide functionality for building complex applications. Just as your desk isn't organized exactly like that of your co-workers, your design environment doesn't have to be the same as anyone else's, either.

A design window may be placed into one of four primary states:

  • Closed
  • Floating
  • Docked
  • Auto hidden

Showing and Hiding Design Windows

[wax ka badal]

When a design window is closed, it doesn't appear anywhere. There is a difference between being closed and being hidden, as you'll learn shortly. To display a closed or hidden window, choose the corresponding menu item from the View menu. For example, if the Properties window isn't displayed in your design environment, you can display it by choosing Properties Window on the View menu (or press its keyboard shortcut�F4). Whenever you need a design window and can't find it, use the View menu to display it. To close a design window, click its Close button (the button on the right side of the title bar with the X on it), just as you would close an ordinary window.

Floating Design Windows

[wax ka badal]

Floating design windows are visible windows that float over the workspace, as shown in [Figure 2.5]. Floating windows are like typical application windows in that you can drag them around and place them anywhere you please, even on other monitors when you're using a multiple-display setup. In addition to moving a floating window, you can also change its size by dragging a border.

Figure 2.5. Floating windows appear over the top of the design environment.


Docking Design Windows

[wax ka badal]

Visible windows appear docked by default. A docked window is a window that appears attached to the side, top, or bottom of the work area or to some other window. The Properties window in [Figure 2.4], for example, is docked to the right side of the design environment. To make a floating window a docked window, drag the title bar of the window toward the edge of the design environment to which you want to dock the window. As you drag the window, you'll drag a rectangle that represents the outline of the window. When you approach an edge of the design environment, the rectangle will change shape and "stick" in a docked position. If you release the mouse while the rectangle appears this way, the window will be docked. Although this is hard to explain, it's very easy to do.

Book - Pencil
You can size a docked window by dragging its edge opposite the side that's docked. If two windows are docked to the same edge, dragging the border between them enlarges one while shrinking the other.


To try this, you'll need to float a window that's already docked. To float a window, you "tear" the window away from the docked edge by dragging the title bar of the docked window away from the edge to which it is docked. Note that this technique won't work if a window is set to Auto Hide (which is explained next). Try docking and floating windows now by following these steps:

  1. Ensure that the Properties window is currently displayed (if it's not, show it using the View menu). Make sure the Properties window isn't set to Auto Hide by right-clicking its title bar and deselecting Auto Hide (if it's selected) from the shortcut menu, as shown in [Figure 2.6].

Figure 2.6. You can't float a window that's set to Auto Hide.

  1. Drag the title bar of the Properties window away from the docked edge. When the rectangle representing the border of the window changes shape, release the mouse button. The Properties window should now appear floating.
  2. Dock the window once more by dragging the title bar toward the right edge of the design environment. Again, release the mouse button when the rectangle changes shape.
Bulb
If you don't want a floating window to dock, regardless of where you drag it to, right-click the title bar of the window and choose Floating from the context menu. To allow the window to be docked again, right-click the title bar and choose Dockable.


Auto Hiding Design Windows 

A feature of C# design environment is the capability to auto hide windows. Although you might find this a bit disconcerting at first, after you get the hang of things, this is a very productive way in which to work because your workspace is freed up, yet design windows are available by simply moving the mouse. Windows that are set to Auto Hide are always docked; you can't set a floating window to Auto Hide. When a window auto hides, it appears as a tab on the edge to which it's docked�much like minimized applications are placed in the Windows taskbar.

Look at the left edge of the design environment in [Figure 2.6]. Notice the two tabs on the left side of the IDE. One tab has a picture of two computers, and the other is labeled Toolbox. These tabs represent auto-hidden windows. To display an auto-hidden window, move the pointer over the tab representing the window. When you move the pointer over a tab, C# displays the design window so that you can use its features. When you move the pointer away from the window, the window automatically hides itself�hence the name. To make any window hide itself automatically, right-click its title bar and select Auto Hide from its shortcut menu. Alternatively, you can click the little picture of a pushpin appearing in the title bar next to the Close button to toggle the window's Auto Hide state.

Performing Advanced Window Placement

[wax ka badal]

The techniques discussed in this section so far are basic methods for customizing your design environment. Things can actually get a bit more complicated if you want them to. Such complication presents itself primarily as the capability to create tabbed floating windows like the one shown in [Figure 2.5]. Notice that at the bottom of the floating window is a set of tabs. Clicking a tab shows its corresponding design window, replacing the window currently displayed. These tabs are created much the same way in which you dock and undock windows�by dragging and dropping. For instance, to make the Solution Explorer window a floating window of its own, you would drag the Solution Explorer window tab away from the floating window. As you do so, a rectangle appears, showing you the outline of the new window. Where you release the rectangle determines whether you dock the design window you're dragging or whether you make the window floating. To make a design window a new tab of an already floating window, drag its title bar and drop it in the title bar of a window that is already floating.

In addition to creating tabbed floating windows, you can dock two floating windows together. To do this, drag the title bar of one window over another window (other than over the title bar) until the shape changes, and then release the mouse. [Figure 2.7] shows two floating windows that are docked to one another and a third window that is floating by itself.

Figure 2.7. Floating, docked, floating and docked�the possibilities are numerous!

Using all the techniques discussed here, you can tailor the appearance of your design environment in all sorts of ways. There is no one best configuration. You'll find that different configurations work better for different projects and in different stages of development. For instance, when I'm designing the interface of a form, I want the toolbox to stay visible but out of my way, so I tend to make it float, or I turn off its Auto Hide property and leave it docked to the left edge of the design environment. However, after the majority of the interface elements have been added to a form, I want to focus on code. Then I dock the toolbox and make it auto hide itself; it's there when I need it, but it's out of the way when I don't. Don't be afraid to experiment with your design windows, and don't hesitate to modify them to suit your changing needs.

Working with Toolbars

[wax ka badal]

Toolbars are the mainstay for performing functions quickly in almost all Windows programs (you'll probably want to add them to your own programs at some point, and [Hour 9], "Adding Menus and Toolbars to Forms," shows you how). Every toolbar has a corresponding menu item, and buttons on toolbars are essentially shortcuts to their corresponding menu items. To maximize your efficiency when developing with C#, you should become familiar with the available toolbars. As your C# skills progress, you can customize existing toolbars and even create your own toolbars to more closely fit the way you work.

Showing and Hiding Toolbars

[wax ka badal]

C# includes a number of built-in toolbars for you to use when creating projects. Two toolbars are visible in most of the figures shown so far in this hour. The one on the top is the Standard toolbar, which you'll probably want displayed all the time. The second toolbar is the Layout toolbar, which provides useful tools for building forms.

The previous edition of Visual Studio had about 5 toolbars; Visual Studio .NET, on the other hand, has more than 20 toolbars! The toolbars you'll use most often as a C# developer are the Standard, Text Editor, and Debug toolbars. Therefore, this hour discusses each of these. In addition to these predefined toolbars, you can create your own custom toolbars to contain any functions you think necessary, which you'll learn how to do later in this hour.

To show or hide a toolbar, choose View, Toolbars to display a list of available toolbars. Toolbars currently displayed appear selected (see [Figure 2.8]). Click a toolbar name to toggle its visible state.

Figure 2.8. Hide or show toolbars to make your work more efficient.

Bulb
A quick way to access the list of toolbars is to right-click any visible toolbar.


Docking and Resizing Toolbars 

Just as you can dock and undock C#'s design windows, you can dock and undock the toolbars. Unlike the design windows, however, C#'s toolbars don't have a title bar that you can click and drag when they're in a docked state. Instead, each docked toolbar has a drag handle (a set of horizontal lines along its left edge). To float (undock) a toolbar, click and drag the grab handle away from the docked edge. After a toolbar is floating, it has a title bar. To dock a floating toolbar, click and drag its title bar to the edge of the design environment to which you want it docked. This is the same technique you use to dock design windows.

Bulb
A shortcut for docking a toolbar is to double-click its title bar.


Although you can't change the size of a docked toolbar, you can resize a floating toolbar (a floating toolbar behaves like any other normal window). To resize a floating toolbar, move the pointer over the edge you want to stretch and then click and drag to the border to change the size of the toolbar.

Customizing Toolbars

[wax ka badal]

As your experience with C# grows, you'll find that you use certain functions repeatedly. To increase your productivity, you can customize any of C#'s toolbars, and you can create your own from scratch. You can even customize the C# menu and create your own menus. To customize toolbars and menus, you use the Customize dialog box shown in [Figure 2.9], which is accessed by choosing View, Toolbars, Customize.

Figure 2.9. Create new toolbars or customize existing ones to fit the way you work.


Book - Pencil
I strongly suggest that you don't modify the existing C# toolbars. Instead, create new toolbars. If you modify the predefined toolbars, you may find that you've removed tools that I refer to in later examples. If you do happen to change a built-in toolbar, you can reset it to its original state by selecting it in the Customize dialog box and clicking Reset.


The Toolbars tab on the Customize dialog box shows you a list of all the existing toolbars and menus. The toolbars and menus currently visible have a check mark next to them. To toggle a toolbar or menu between visible and hidden, click its check box.

Creating a New Toolbar

[wax ka badal]

You're now going to create a new toolbar to get a feel for how toolbar customization works. Your toolbar will contain only a single button, which will be used to call C#'s Help program.

To create your new toolbar, follow these steps:

  1. From the Toolbars tab of the Customize dialog box, click New.
  2. Enter My Help as the name for your new toolbar when prompted.
  3. Click OK to create the new toolbar.

After you've entered a name for your toolbar and clicked OK, your new toolbar appears, floating on the screen�most likely somewhere outside the Customize dialog box (see [Figure 2.10]). Dock your toolbar now by double-clicking the blank area on the toolbar (the area where a button would ordinarily appear). Your screen should look like the one in [Figure 2.11].

Figure 2.10. New toolbars are pretty tiny; they have no buttons on them.

Figure 2.11. It's easier to customize toolbars when they're docked.

Adding Buttons to a Toolbar

[wax ka badal]

Now that you have an empty toolbar, the next step is to add the desired command buttons to it. Click the Commands tab of the Customize dialog box to display all the available commands.

The Commands tab contains the following:

  • A list of command categories
  • A list of the commands for the selected command category

The Categories list shows all available command categories, such as File and Edit functions. When you select a category, all the available commands for that category are shown in the list on the right.

You're going to add a toolbar button that appears as a Help icon and that actually displays Help when clicked.

To add the command button to your toolbar, follow these steps:

  1. Locate and select the category Help. All the available commands for the Help category will appear in the list on the right.
  2. From the Commands list, click and drag the Contents command to your custom toolbar. As you drag, the pointer changes to an arrow pointing to a small gray box. At the lower-right corner of the pointer is a little hollow box with an x in it. This indicates that the location over which the pointer is positioned is not a valid location to drop the command.
  3. As you drag the command over your toolbar (or any other toolbar for that matter), the x in the little box will change to a plus sign (+), indicating that the command can be placed in the current location. In addition, an insertion point (often called an I-beam because that's what it looks like) appears on the toolbar to indicate where the button would be placed if the command were dropped at that spot. When an I-beam appears on your toolbar and the pointer box contains a plus sign, release the mouse button. Your toolbar will now look like the one in [Figure 2.12].

Figure 2.12. Building toolbars is a simple matter of dragging and dropping commands.

You can alter any button on a toolbar by right-clicking the button to access its shortcut menu and then choosing Change Button Image. Feel free to experiment with changing the image of the button on your custom toolbar, but be sure to leave the buttons on the built-in toolbars as they are.

To remove a button from a toolbar, drag the button to remove it from the toolbar and drop it somewhere other than on the same toolbar. If you drop the button onto another toolbar, the button is removed from the original toolbar and placed on the toolbar on which you dropped it. If you drop the button in a location where no toolbar exists, the button is simply removed from the toolbar.

Book - Pencil
You can drag command buttons only in Customize mode. If you attempt to drag an item during normal operation, you'll simply click the button.
Bulb
Although these techniques are illustrated using toolbars, they apply to menus, as well.


Moving Buttons on a Menu or Toolbar 

You should always attempt to group command buttons logically. For example, the Edit functions are all grouped together on the Standard toolbar, as are the File operations. A separator (space) is used to separate groups. To create a separator space, right-click the button that starts a new group and choose Begin a Group from the button's shortcut menu.

You probably won't get the exact groupings you want when you first add commands to a toolbar, but that's not a problem because you can change the position of a button at any time. To move a button on a toolbar, drag the button and drop it in the desired location (remember, you have to be in Customize mode to do this). To move a button from one toolbar to another, drag the button from its toolbar and drop it at the preferred location on the desired toolbar.

Now that your toolbar is complete (Hey, I never said it'd be fancy), click Close on the Customize dialog box to exit Customize mode. All toolbars, including the one you just created, are no longer in Customize mode and they can't be modified. Click the button you placed on your new toolbar and C#'s Help will appear.

Because your custom toolbar really doesn't do much, hide it now to save screen real estate by right-clicking any toolbar to display the Toolbar shortcut menu and then deselecting My Help.

Book - Pencil
As you work your way through this book, you should always have the Standard toolbar and menu bar displayed on your screen.


Typically, you should customize toolbars only after you're very familiar with the available functions and only after you know which functions you use most often. I recommend that you refrain from modifying any of the predefined toolbars until you're quite familiar with C#. As you become more comfortable with C#, you can customize the toolbars to make your project work area as efficient as possible.


Adding Controls to a Form Using the Toolbox

The toolbox is used to place controls, such as the common text box and list box, onto a form. The default toolbox you see when you first run C# is shown in [Figure 2.13]. The buttons labeled Data, Components, Windows Forms, and so on are actually tabs, although they don't look like standard tabs. Clicking any of these tabs causes a related set of controls to appear. The default tab is the Windows Forms tab, and it contains many great controls you can place on Windows forms (the forms used to build Windows applications, in contrast to Web applications). All the controls that appear by default on the tabs are included with C#, and these controls are discussed in detail in [Hour 7], "Working with Traditional Controls," and [Hour 8], "Advanced Controls." You'll learn how to add other controls to your toolbox as well.

Figure 2.13. The standard toolbox contains many useful controls you can use to build robust user interfaces.

You can add a control to a form in one of three ways:

  • In the toolbox, click the tool that you want to place on a form, and then click and drag on the form where you want the control placed (essentially, you're drawing the border of the control). The location at which you start dragging is used for the upper-left corner of the control, and the lower-right corner is the point at which you release the mouse button and stop dragging.
  • Double-click the desired control in the toolbox. When you double-click a control in the toolbox, a new control of the selected type is placed in the upper-left corner of the form. The control's height and width are set to the default height and width of the selected control type.
  • Drag a control from the toolbox and drop it somewhere on a form.
Bulb
If you prefer to draw controls on your forms by clicking and dragging, I strongly suggest that you dock the toolbox to the right or bottom edge of the design environment or float it; the toolbar tends to interfere with drawing controls when it's docked to the left edge, because it obscures part of the form.


The very first item on the Windows Forms tab, titled Pointer, isn't actually a control. When the pointer item is selected, the design environment is placed in a select mode rather than in a mode to create a new control. With the pointer item selected, you can select a control (by clicking it) to display all its properties in the Properties window; this is the default behavior.

Setting Object Properties Using the Properties Window 

When developing the interface of a project, you'll spend a lot of time viewing and setting object properties using the Properties window (see [Figure 2.14]). The Properties window contains four items:

  • An object drop-down list
  • A list of properties
  • A set of tool buttons used to change the appearance of the properties grid
  • A section showing a description of the selected property

Figure 2.14. Use the Properties window to view and change properties of forms and controls.

Selecting an Object and Viewing Its Properties

[wax ka badal]

The drop-down list at the top of the Properties window contains the name of the form with which you're currently working and all the controls (objects) on the form. To view the properties of a control, select it from the drop-down list or click the control on the form. You must have the pointer item selected in the toolbox to select an object by clicking it.

Viewing and Changing Properties

[wax ka badal]

The first two buttons in the Properties window (Categorized and Alphabetic), enable you to select the format in which you view properties. When you select the Alphabetic button, the selected object's properties are listed in the Properties window in alphabetical order. When you click the Categorized button, all the selected object's properties are displayed by category. For example, the Appearance category contains properties such as BackColor and BorderStyle. When working with properties, select the view you're most comfortable with and feel free to switch back and forth between the views.

The Properties pane of the Properties window is used to view and set the properties of a selected object. You can set a property in one of the following ways:

  • Type in a value
  • Select a value from a drop-down list
  • Click a Build button for property-specific options
Book - Pencil
Many properties can be changed by more than one of these methods.


To better understand how changing properties works, follow these steps:

  1. Start by creating a new Windows Application project. Name this project Changing Properties.
  2. Add a new text box to a form by double-clicking the TextBox tool in the toolbox. You're now going to change a few properties of the new text box.
  3. Select the Name property in the Properties window by clicking it, and then type in a name for the text box�call it txtComments.
  4. Click the BorderStyle property and try to type in the word Big�you can't; the BorderStyle property supports only selecting values from a list. You can type a value that exists in the list, however. When you selected the BorderStyle property, a drop-down arrow appeared in the value column. Click this arrow now to display a list of the values that the BorderStyle property accepts. Select FixedSingle and notice how the appearance of the text box changes. To make the text box appear three dimensional again, open the drop-down list and select Fixed3D.
  5. Select the BackColor property, type in some text, and press the Tab key to commit your entry. C# displays an Invalid Property Value error. This happened because, although you can type in text, you're restricted to entering specific values (in the case of BackColor, the value must be a number within a specific range or a named color). Click the drop-down arrow of the BackColor property and select a color from the drop-down list. (Selecting colors using the Color Palette is discussed later in this hour, and detailed information on using colors is provided in [Hour 10], "Drawing and Printing.")
  6. Select the Font property. Notice that a Build button appears (a small button with three dots on it). When you click the Build button, a dialog box specific to the property you've selected appears. In this instance, a dialog box that allows you to manipulate the font of the text box appears (see [Figure 2.15]). Different properties display different dialog boxes when you click their Build buttons.

Figure 2.15. The Font dialog box gives you complete authority over the font of a control.


By clicking a property in the Properties window, you can easily tell the type of input the property requires.

Working with Color Properties

[wax ka badal]

Properties that deal with colors, such as BackColor and ForeColor, are unique in the way in which they accept values, yet all color-related properties behave the same way. In C#, all colors are expressed as a set of three numbers, each number having a value from 0 to 255. The set of numbers represents the Red, Green, and Blue (RGB) components of the color, respectively.

Book - Pencil
The value 0,255,0, for instance, represents pure green, whereas the values 0,0,0 represent black and 255,255,255 represents white. (See [Hour 10] for more information on the specifics of working with color.)


A color rectangle is displayed for each color property in the Properties window; this color is the selected color for the property. Text is displayed next to the colored rectangle. This text is either the name of a color or a set of RGB values that defines the color. Clicking in a color property causes a drop-down arrow to appear, but the drop-down you get by clicking the arrow isn't a typical drop-down list. [Figure 2.16] shows what the drop-down list for a color property looks like.

Figure 2.16. The color drop-down list enables you to select from three sets of colors.


The color drop-down list is composed of three tabs: Custom, Web, and System. Most color properties use a system color by default. [Hour 10] goes into great detail on system colors, so I only want to mention here that system colors vary from computer to computer; they are the colors determined by the user when he or she right-clicks the desktop and chooses Properties from the desktop's shortcut menu. Use a system color when you want a color to be one of the user's selected system colors. When a color property is set to a system color, the name of the color appears in the property sheet.

The Custom tab shown in [Figure 2.17] is used to specify a specific color, regardless of the user's system color settings; changes to system colors have no effect on the property. The most common colors appear on the palette of the Custom tab, but you can specify any color you desire.

Figure 2.17. The Custom tab of the color drop-down list lets you specify any color imaginable.


Book - Pencil
The colors visible in the various palettes are limited by the number of colors that can be produced by your video card. If your video card doesn't support enough colors, some will appear dithered, which means they will appear as dots of colors rather than as a true, solid color.


The bottom two rows in the Custom color palette are used to mix your own colors. To assign a color to an empty color slot, right-click a slot in one of the two rows to access the Define Color dialog box (see [Figure 2.18]). Use the controls on the Define Color dialog box to create the color you desire, and then click Add Color. The new color appears on the color palette in the slot you selected, and it is automatically assigned to the current property.

Figure 2.18. The Define Color dialog box lets you create your own colors.


The Web tab is used to pick colors from a list of named colors for building Web pages.

Viewing Property Descriptions

[wax ka badal]

It's not always immediately apparent just exactly what a property is or does�especially for new users of Visual Studio. The Description section at the bottom of the Properties window shows a simple description of the selected property (refer to [Figure 2.14]). To view a description, simply click a property or value area of a property.

You can hide or show the Description section of the Properties window at any time by right-clicking anywhere within the Properties window (other than in the value column or on the title bar) to display the Properties window shortcut menu and choosing Description. Each time you do this, you toggle the Description section between visible and hidden. To change the size of the Description box, click and drag the border between it and the Properties pane.

Managing Projects 

Before you can effectively create an interface and write code, you need to understand what makes up a C# project and how to add and remove various components from within your own projects. In this section, you'll learn about the Solution Explorer window and how it's used to manage project files. You'll also learn specifics about projects and project files, as well as how to change a project's properties.

Managing Project Files with the Solution Explorer 

As you develop projects, they'll become more and more complex, often containing many objects such as forms and modules. Each object is defined by one or more files. In addition, you can build complex solutions composed of more than one project. The Solution Explorer window shown in [Figure 2.19] is the tool for managing all the files in a simple or complex solution. Using the Solution Explorer, you can add, rename, and remove project files, as well as select objects to view their properties. If the Solution Explorer window isn't visible on your screen, show it now by choosing Solution Explorer from the View menu.

Figure 2.19. Use the Solution Explorer window to manage all the files that make up a project.

To better understand the Solution Explorer window, follow these steps:

  1. Locate the Picture Viewer program you created in the Quick Tour by choosing File, Open, and then clicking Project.
  2. Open the Picture Viewer project. The file you need to select is located in the Picture Viewer folder that C# created when the project was constructed. The file has the extension .sln (for solution). If you're asked whether you want to save the current project, choose No.
  3. Select the Picture Viewer project item in the Solution Explorer. When you do, a button becomes visible toward the top of the window. This button has a picture of pieces of paper and has the ToolTip Show All Files (see [Figure 2.20]). Click this button and the Solution Explorer displays all files in the project.

Figure 2.20. Notice that the form you defined appears as two files in the Solution Explorer.

Your design environment should now look like the one in [Figure 2.20]. If your screen looks much different from the one in this figure, use the techniques you've learned in this hour to change your design environment so that it's similar to the one shown here. Be sure to widen the Solution Explorer window so that you can read all the text it contains.

Book - Pencil
Some forms and other objects may be composed of more than one file. By default, C# hides project files that you don't directly manipulate. Click the plus sign (+) next to the form item and you'll see a sub item titled Form1.resx. You'll learn about these additional files in [Hour 5], "Building Forms�Part I." For now, click the Show All Files button again to hide these related files.


You can view any object listed within the Solution Explorer using the object's default viewer by double-clicking the object. Each object has a default viewer but may actually have more than one viewer. For instance, a form has a Form Design view as well as a Code view. By default, double-clicking a form in the Solution Explorer displays the form in Form Design view, where you can manipulate the form's interface.

You've already learned one way to access the code behind a form�double-click an object to access its default event handler. You'll frequently need to get to the code of a form without adding a new event handler. One way to do this is to use the Solution Explorer. When a form is selected in the Solution Explorer, buttons are visible at the top of the Solution Explorer window that allow you to display the code editor or the form designer, respectively.

You'll use the Solution Explorer window so often that you'll probably want to dock it to an edge and set it to Auto Hide, or perhaps keep it visible all the time. The Solution Explorer window is one of the easiest to get the hang of in C#; navigating the Solution Explorer window will be second nature to you before you know it.

Working with Solutions

[wax ka badal]

In truth, the Solution Explorer window is the evolution of the Project Explorer window from versions of Visual Studio prior to .NET, and the two are similar in many ways. Understanding solutions is easier to do when you understand projects.

A project is what you create with C#. Often, the words project and program are used interchangeably; this isn't much of a problem if you understand the important distinctions. A project is the set of source files that make up a program or component, whereas a program is the binary file that you build by compiling source files into something such as a Windows executable file (.exe). Projects always consist of a main project file and may be made up of any number of other files, such as form files, module files, or class module files. The main project file stores information about the project�all the files that make up the project, for example�as well as properties that define aspects of a project, such as the parameters to use when the project is compiled into a program.

What then, is a solution? As your abilities grow and your applications increase in complexity, you'll find that to accomplish your development goals, you'll have to build multiple projects that work harmoniously. For instance, you might build a custom user control such as a custom data grid that you use within other projects you design, or you may isolate the business rules of a complex application into separate components to run on isolated servers. All the projects used to accomplish those goals are collectively called a solution. Therefore, a solution (at its most basic level) is really nothing more than a grouping of projects.

Bulb
You should group projects into a single solution only when the projects relate to one another. If you have a number of projects that you're working on, but each of them is autonomous, work with each project in a separate solution.


Understanding Project Components 

As I stated earlier, a project always consists of a main project file, and it may consist of one or more secondary files, such as files that make up forms or code modules. As you create and save objects within your project, one or more corresponding files are created and saved on your hard drive. All files that are created for C# source objects have the extension .cs, designating that they define C# objects. Make sure that you save your objects with understandable names, or things might get confusing as the size of your project grows.

All the files that make up a project are text files. Some objects, however, need to store binary information, such as a picture, for a form's BackgroundImage property. Binary data is stored in an XML file (which is still a text file). Suppose you had a form with an icon on it. You'd have a text file defining the form (its size, the controls on it, and the code behind it), and an associated resource file with the same name as the form file but with the extension .resx. This second file would be in XML format and would contain all the binary data needed to create the form.

Book - Pencil
If you want to see what the source file of a form file looks like, use Notepad to open a form file on your computer. Don't save any changes to the file, however, or it may never work again.


The following is a list of some of the components you may use in your projects:

  • Forms Forms are the visual windows that make up the interface of your application. Forms are defined using a special type of module.
  • Class Modules Class modules are a special type of module that enable you to create object-oriented applications. Throughout the course of this book, you're learning how to program using an object-oriented language, but you're mostly learning how to use objects supplied by C#. In [Hour 17], "Designing Objects with Classes," you'll learn how to use class modules to create your own objects. Forms are derived from a special type of class module.
  • User Controls User controls (formerly ActiveX controls, which are formerly OLE controls) are controls that can be used on the forms of other projects. For example, you could create a User control with a calendar interface for a contact manager. Creating user controls requires the skill of an experienced programmer; therefore, I won't be covering them in this book.

Setting Project Properties

[wax ka badal]

C# projects have properties, just as other objects do, such as forms and controls. Projects have lots of properties, many of them relating to advanced functionality that I won't be covering in this book. However, you need to be aware of how to access project properties and how to change some of the more commonly used properties.

To access the properties for a project, right-click the project in the Solution Explorer window and choose Properties from the shortcut menu. Do this now.

Book - Pencil
In earlier versions of Visual Studio, you accessed the project properties via the Project menu. You can still do this, but you must have the project selected in the Solution Explorer, or the Properties menu won't appear on the Project menu. If you don't remember this, you could spend a lot of time trying to find the properties�I sure did.


The Tree View control on the left side of the dialog box is used to display a property page (see [Figure 2.21]). When you first open the dialog box, the General page is visible. On this page, the setting you'll need to worry about most is the Startup Object property. The Startup Object setting determines the name of the class that contains the Main() method that you want called on program startup. The (Not Set) option, as shown in [Figure 2.21], is valid if only one Main() method exists in your application.

Figure 2.21. Project properties let you tailor aspects of the project as a whole.

The Output Type option determines the type of compiled component defined by this source project. When you create a new project, you select the type of project to create (such as Windows Application), so this field is always filled in. At times, you might have to change this setting after the project has been created, and this is the place to do so.

Notice that the project folder, project filename, and output name are displayed on this page as well. If you work with a lot of projects, you may find this information valuable, and this is certainly the easiest spot to obtain it.

Book - Pencil
The output name determines the filename created when you build a distributable component. Distributing applications is discussed in [Hour 22].


As you work through the hours in this book, I'll refer to the Project Properties dialog box as necessary, explaining pages and items in context with other material.

Adding and Removing Project Files

[wax ka badal]

When you first start C# and create a new Windows Application project, C# creates the project with a single form. You're not limited to having one form in a project, however; you can create new forms or add existing forms to your project at will. You can also create and add code files and classes, as well as other types of objects.

You can add a new or existing object to your project in one of three ways:

  • Choose the appropriate menu item from the Project menu.
  • Click the small drop-down arrow that is part of the Add New Item button on the Standard toolbar, and then choose the object type from the drop-down list that is displayed (see [Figure 2.22]).
  • Right-click the project name in the Solution Explorer window, and then choose Add from the shortcut menu to access a submenu from which you can select object types.

When you select Add ObjectType from any of these menus, a dialog box appears, showing you the objects that can be added to the project. Your chosen item is selected by default (see [Figure 2.23]). Simply name the object and click Open to create a new object of the selected type. To create an object of a different type, click the type to select it, name it, and then click Open.

Figure 2.23. Regardless of the menu option you select, you can add any type of object you want using this dialog box.

Adding new forms and modules to your project is easy, and you can add as many as you like. You'll come to rely more heavily on the Solution Explorer to manage all the objects in the project as the project becomes more complex.

Although it won't happen as often as adding project files, you may sometimes need to remove an object from a project. Removing objects from your project is even easier than adding them. To remove an object, simply right-click the object in the Solution Explorer window and select Exclude from Project. This removes the object from the file but does not delete the source file from the disk. Selecting Delete, on the other hand, removes the file from the project and deletes it from the disk. Don't select Delete unless you want to totally destroy the file and you're sure that you'll never need it again in the future.

Getting Help 

Although C# was designed to be as intuitive as possible, you'll find that you occasionally need assistance in performing a task. It doesn't matter how much you know, C# is so complex and contains so many features that you'll have to use Help sometimes. This is particularly true when writing C# code; you won't always remember the command you need or the syntax of the command. Fortunately, C# includes a comprehensive Help feature.

To access Help from within the design environment, press F1. Generally speaking, when you press F1, C# shows you a help topic directly related to what you're doing. This is known as context-sensitive help, and when it works, it works well. For example, you can display help for any C# syntax or keyword (functions, objects, methods, properties, and so on) when writing C# code by typing the word into the code editor, positioning the cursor anywhere within the word (including before the first letter or after the last), and pressing F1. You can also get to help from the Help menu on the menu bar.

Book - Pencil
C#'s Help won't be displayed if your program is in Run mode when you press F1. Instead, the help for your application will appear�if you've created Help.


Help displays topics directly within the design environment instead of in a separate window. This is a new feature of .NET. Personally, I think this method is considerably inferior to the old style of Visual Studio having Help float above the design environment. When Help is displayed within the design environment, you can't necessarily see the code, form, or other object with which you're working. To make Help float above the design environment, choose Options from the Tools menu to display the Options dialog box, click Help in the Tree view on the left, and select External Help.

C# includes a Help feature called Dynamic Help. To display the Dynamic Help window, choose Dynamic Help from the Help menu. The Dynamic Help window shows Help links related to what it is you're working on (see [Figure 2.24]). For instance, if you select a form, the contents of the Dynamic Help window show you Help links related to forms. If you click a text box, the contents of the Dynamic Help window adjust to show you Help links related to text boxes. This is an interesting feature, and you may find it valuable.

Summary

[wax ka badal]

In this hour, you learned how to use the Visual Studio Start page�your gateway to C#. You learned how to create new projects and how to open existing projects. The C# environment is your workspace, toolbox, and so much more. You learned how to navigate the environment, including how to work with design windows (hide, show, dock, and float).

You'll use toolbars constantly, and now you know how to modify them to suit your specific needs. You learned how to create new toolbars and how to modify existing toolbars. This is an important skill that shouldn't be overlooked.

C# has many different design windows, and in this hour, you began learning about some of them in detail. You learned how to get and set properties using the Properties window, how to manage projects using the Solution Explorer, and how to add controls to a form using the toolbox. You'll use these skills often, so it's important to get familiar with them right away. Finally, you learned how to access C#'s Help feature, which I guarantee you will find very important as you learn to use C#.

C# is a vast and powerful development tool. Don't expect to become an expert overnight; this is simply impossible. However, by learning the tools and techniques presented in this hour, you've begun your journey. Remember, you'll use most of what you learned in this hour each and every time you use C#. Get proficient with these basics and you'll be building cool programs in no time!

[Q1: How can I easily get more information about a property when the Description section of the Properties window just doesn't cut it?
A1: Click the property in question to select it, and then press F1; context-sensitive help applies to properties in the Properties window, as well.
[Q2: I find that I need to see a lot of design windows at one time, but I can't find that "magic" layout. Any suggestions?
A2: Run at a higher resolution. Personally, I won't develop in less than 1024x768. As a matter of fact, all my development machines have two displays, both running at this resolution. You'll find that any investment you make in having more screen real estate will pay you big dividends.


Workshop

[wax ka badal]

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 [Appendix A], "Answers to Quizzes/Exercises."

[ 1: How can you make the Visual Studio Start Page appear at startup if this feature has been disabled?
[ 2: Unless instructed otherwise, you are to create what type of project when building examples in this book?
[ 3: To make a docked design window appear when you hover over its tab and disappear when you move the mouse away from it, you change what setting of the window?
[ 4: How do you access the Toolbars menu?
[ 5: What design window do you use to add controls to a form?
[ 6: What design window is used to change the attributes of an object?
[ 7: To modify the properties of a project, you must select the project in what design window?
[ 8: Which Help feature adjusts the links it displays to match what it is you are doing?


 Exercises
  1. Create a custom toolbar that contains Save All, Start, and Stop Debugging�three buttons you'll use a lot throughout this book.
  2. Use the Custom Color dialog box to create a color of your choice, and then assign the color to the BackColor property of a form.

Hour 3. Understanding Objects and Collections

[wax ka badal]

So far, you've gotten an introduction to programming in C# by building a Picture Viewer project. You spent the previous hour digging into the IDE and learning skills critical to your success with C#. In this hour, you're going to start learning about some important programming concepts, namely objects.

New term
The term object, as it relates to programming, may have been new to you prior to this book. The more you work with C#, the more you'll hear about objects. C# is a true object-oriented language. This hour isn't going to discuss object-oriented programming in any detail, because object-oriented programming is a very complex subject and is well beyond the scope of this book. Instead, you'll learn about objects in a more general sense. Everything you use in C# is an object, so understanding this material is critical to your success with C#. Forms are objects, for example, as are the controls you place on a form. Pretty much every element of a C# project is an object and belongs to a collection of objects. All objects have attributes (called properties), most have methods, and many have events. Whether creating simple applications or building large-scale enterprise solutions, you must understand what an object is and how it works. In this hour, you'll learn what makes an object an object, and you'll learn about collections.


The highlights of this hour include the following:

  • Understanding objects
  • Getting and setting properties
  • Triggering methods
  • Understanding method dynamism
  • Writing object-based code
  • Understanding collections
  • Using the Object Browser
Book - Pencil
If you've listened to the programming press at all, you've probably heard the term object oriented, and perhaps words such as polymorphism, encapsulation, and inheritance. In truth, these object-oriented features of C# are very exciting, but they're far beyond [03.htm#ch03 Hour 3]. You'll learn a little about object-oriented programming in this book, but if you're really interested in taking your programming skills to the next level, you should buy a book dedicated to the subject after you've completed this one.



Understanding Objects

[wax ka badal]

Object-oriented programming has been a technical buzzword for quite some time. Almost everywhere you look�the Web, publications, books�you read about objects. What exactly is an object? Strictly speaking, it is a programming structure that encapsulates data and functionality as a single unit and for which the only public access is through the programming structure's interfaces (properties, methods, and events). In reality, the answer to this question can be somewhat ambiguous because there are so many types of objects�and the number grows almost daily. However, all objects share specific characteristics, such as properties and methods.

The most commonly used objects in Windows applications are the form object and the control object. Earlier hours introduced you to working with forms and controls and even showed you how to set form and control properties. In your Picture Viewer project from [Hour 1], for instance, you added a picture box and two buttons to a form. Both the PictureBox and the Button control are control objects, but each is a specific type of control object. Another, less-technical example uses pets. Dogs and cats are definitely different entities (objects), but they both fit into the category of Pet objects. Similarly, text boxes and buttons are each a unique type of object, but they're both considered a control object. This small distinction is important.

Understanding Properties 

All objects have attributes used to specify and return the state of the object. These attributes are properties, and you've already used some of them in previous hours using the Properties window. Indeed, every object exposes a specific set of properties, but not every object exposes the same set of properties. To illustrate this point, I will continue with the Pet object concept. Suppose you have an object, and the object is a dog. This Dog object has a certain set of properties that are common to all dogs. These properties include attributes such as the dog's name, the color of its hair, and even the number of legs it has. All dogs have these same properties; however, different dogs have different values for these properties. [Figure 3.1] illustrates such a Dog object and its properties.

Figure 3.1. Properties are the attributes that describe an object.

graphics/03fig01.gof

Getting and Setting Properties

[wax ka badal]

You've already seen how to read and change properties using the Properties window. The Properties window is available only at design time, however, and is used only for manipulating the properties of forms and controls. Most reading and changing of properties you'll perform will be done with C# code, not by using the Properties window. When referencing properties in code, you specify the name of the object first, followed by a period (.), and then the property name, as in the following syntax:

{ObjectName}.{Property}

If you had a Dog object named Bruno, for example, you would reference Bruno's hair color this way:

Bruno.HairColor

This line of code would return whatever value was contained in the HairColor property of the Dog object Bruno. To set a property to some value, you use an equal (=) sign. For example, to change the Dog object Bruno's Weight property, you would use a line of code such as the following:

Bruno.Weight = 90;
Book - Pencil
A little later in this hour, I discuss instantiation, which is the process of creating an object based on a template. It's important to note here that Bruno is a named instance of an object derived from a template or blueprint (called a class). Each object instance has its own set of data, such as property values. For example, you could also have a Dog object named Bonnie, which has a unique set of properties. In a more real-world example, consider how you can have two buttons on a form. Although they have different property values (such as Name), and they have different code within their Click events, they are both Button objects.


When you reference a property on the left side of an equal sign, you're setting the value. When you reference a property on the right side of the equal sign, you're getting (reading) the value.

Bruno.Weight = 90;

It's easier to see here that referencing the property on the left side of the equal sign indicates that you are setting the property to some value.

The following line of code places the value of the Weight property of the Dog object called Bruno into a temporary variable. This statement retrieves the value of the Weight property because the Weight property is referenced on the right side of the equal sign.

fltWeight = Bruno.Weight;

Variables are discussed in detail in [Hour 12], "Using Constants, Data Types, Variables, and Arrays." For now, think of a variable as a storage location. When the processor executes this code statement, it retrieves the value in the Weight property of the Dog object Bruno and places it in the variable (storage location) titled Weight. Assuming that Bruno's Weight is 90, as set in the previous example, the computer would process the following code statement:

fltWeight = 90;

Just as in real life, some properties can be read but not changed. Suppose you had a Sex property to designate the gender of a Dog object. It's impossible for you to change a dog from a male to a female or vice versa (at least I think it is). Because the Sex property can be retrieved but not changed, it is a read-only property. You'll often encounter properties that can be set in Design view but become read-only when the program is running.

One example of a read-only property is the Height property of the Combo Box control. Although you can view the value of the Height property in the Properties window, you cannot change the value�no matter how hard you try. If you attempt to change the Height property using C# code, C# simply changes the value back to the default.

Book - Pencil
The best way to determine which properties of an object are read-only is to consult the online help for the object in question.


Working with an Object and Its Properties 

Now that you know what properties are and how they can be viewed and changed, you're going to experiment with properties in a simple project. In [Hour 1], you learned how to set the Height and Width properties of a form using the Properties window. Now, you're going to change the same properties using C# code.

The project you're going to create consists of a form with some buttons on it. One button will enlarge the form when clicked, whereas the other will shrink the form. This is a very simple project, but it illustrates rather well how to change object properties in C# code.

  1. Start by creating a new Windows Application project (from the File menu, choose New, Project).
  2. Name the project Properties Example.
  3. Use the Properties window to change the name of the form to fclsShrinkMe. (Click the form once to select it and press F4 to display the Properties window.)
  4. Next, change the Text property of the form to Grow and Shrink.
  5. Click the View Code button in Solution Explorer to view the code behind the form. Scroll down and locate the reference to Form1 and change it to fclsShrinkMe.
  6. Click the Form1.cs [Design] tab to return to the form designer.

When the project first runs, the default form will have a Height and Width as specified in the Properties window. You're going to add buttons to the form that a user can click to enlarge or shrink the form at runtime.

Add a new button to the form by double-clicking the Button tool in the toolbox. Set the new button's properties as follows:

Property Set To
Name btnEnlarge
Location 111,70
Text Enlarge

Now for the Shrink button. Again, double-click the Button tool in the toolbox to create a new button on the form. Set this new button's properties as follows:

Property Set To
Name btnShrink
Location 111,120
Text Shrink

Your form should now look like the one shown in [Figure 3.2].

Figure 3.2. Each button is an object, as is the form the buttons sit on.

To complete the project, you need to add the small amount of C# code necessary to modify the form's Height and Width properties when the user clicks a button. Access the code for the Enlarge button now by double-clicking the Enlarge button. Type the following statement exactly as you see it here. Do not hit the Enter key or add a space after you've entered this text.

this.Width

When you typed the period, or "dot," as it's called, a small drop-down list appeared, like the one shown in [Figure 3.3]. C# is smart enough to realize that this represents the current object (more on this in a moment), and to aid you in writing code for the object, it gives you a drop-down list containing all the properties and methods of the form. This feature is called IntelliSense, and it is relatively new to Visual Studio. Because C# is fully object-oriented, you'll come to rely on IntelliSense drop-down lists in a big way; I think I'd rather dig ditches than program without them.

Figure 3.3. IntelliSense drop- down lists, or auto-completion drop-down lists, make coding dramatically easier.

Use the Backspace key to completely erase the code you just entered and enter the following code in its place (press Enter at the end of each line):

this.Width = this.Width + 20;
this.Height = this.Height + 20;

Again, the word this refers to the object to which the code belongs (in this case, the form). The word this is a reserved word; it's a word that you cannot use to name objects or variables because C# has a specific meaning for it. When writing code within a form module, as you are doing here, you should always use the this reserved word rather than using the name of the form. this is much shorter than using the full name of the current form, and it makes the code more portable (you can copy and paste the code into another form module and not have to change the form name to make the code work). Also, should you change the name of the form at any time in the future, you won't have to change references to the old name.

Book - Pencil
The word this is the equivalent to the Me reserved word in Visual Basic.


The code you've entered simply sets the Width and Height properties of the form to whatever the current value of the Width and Height properties happens to be, plus 20 pixels.

Redisplay the form designer by selecting the tab titled Form1.cs [Design]; then double-click the Shrink button to access its Click event and add the following code:

this.Width = this.Width � 20;
this.Height = this.Height � 20;

This code is very similar to the code in the Enlarge_Click event, except that it reduces the Width and Height properties of the form by 20 pixels.

Your screen should now look like [Figure 3.4].

Figure 3.4. The code you've entered should look exactly like this.

Bulb
As you create projects, it's a very good idea to save frequently. Save your project now by clicking the Save All button on the toolbar.


Again, display the form designer by clicking the tab Form1.cs [Design]. Your Properties Example is now ready to be run! Press F5 to put the project in Run mode (see [Figure 3.5]).

Figure 3.5. What you see is what you get�the form you created should look just as you designed it.


Click the Enlarge button a few times and notice how the form gets bigger. Next, click the Shrink button to make the form smaller. When you've clicked enough to satisfy your curiosity (or until you get bored), end the running program and return to Design mode by clicking the Stop Debugging button on the toolbar.

Understanding Methods 

In addition to properties, most objects have methods. Methods are actions the object can perform, in contrast to attributes that describe the object. To understand this distinction, think about the Pet object example. A Dog object has a certain set of actions that it can perform. These actions, called methods in C#, include barking and tail wagging. [Figure 3.6] illustrates the Dog object and its methods.

Figure 3.6. Invoking a method causes the object to perform an action.

graphics/03fig06.gof

Triggering Methods

[wax ka badal]

Think of methods as functions�which is exactly what they are. When you invoke a method, code is executed. You can pass data to the method, and methods may return values. However, a method is neither required to accept parameters (data passed by the calling code) nor required to return a value; many methods simply perform an action in code. Invoking (triggering) a method is similar to referencing the value of a property; you first reference the object's name, then a "dot," then the method name, followed by a set of parentheses, which can optionally contain any parameters that must be passed to the method.

{ObjectName}.{Method}();

For example, to make the hypothetical Dog object Bruno bark using C# code, you would use this line of code:

Bruno.Bark();
Book - Pencil
Method calls in C# must always have parentheses. Sometimes they'll be empty, but at other times they'll contain data.


Invoking methods is simple; the real skill lies in knowing what methods an object supports and when to use a particular method.

Understanding Method Dynamism

[wax ka badal]

Properties and methods go hand in hand, and at times a particular method may become unavailable because of one or more property values. For example, if you were to set the NumberofLegs on the Dog object Bruno equal to zero, the Walk and Fetch methods would obviously be inapplicable. If you were to set the NumberofLegs property back to four, you could then trigger the Walk or Fetch methods again. In C#, a method or property won't physically become unavailable�you can still call it, but doing so might cause an exception (error) or the call may be ignored.

>


Building an Object Example Project

The only way to really grasp what objects are and how they work is to use them. I've said this before but I can't say it enough: everything in C# is an object.

You're about to create a sample project that uses objects. If you're new to programming with objects, you'll probably find this a bit confusing. However, I'll walk you through step by step, explaining each section in detail.

The project you're going to create consists of a single form with one button on it. When the button is clicked, a line will be drawn on the form beginning at the upper-left corner of the form and extending to the lower-right corner.

Book - Pencil
In [Hour 10], "Drawing and Printing," you'll learn all about the drawing functionality within C#.


Creating the Interface for the Drawing Project 

Follow these steps to create the interface for your project:

  1. Create a new Windows Application project titled Object Example.
  2. Change the form's Text property to Object Example using the Properties window.
  3. Add a new button to the form and set its properties as shown in the following table:
Property Value
Name btnDraw
Location 112,120
Text Draw
Writing the Object-Based Code 

You're now going to add code to the Click event of the button. I'm going to explain each statement, and at the end of the steps, I'll show the complete code listing.

Object Example Project

[wax ka badal]
  1. Double-click the button to access its Click event.
  2. Enter the first line of code as follows (remember to press Enter at the end of each statement):
System.Drawing.Graphics objGraphics = null;

Objects don't materialize out of thin air; they have to be created. When a form is loaded into memory, it loads all its controls (that is, creates the control objects), but not all objects are created automatically like this. The process of creating an instance of an object is called instantiation. When you load a form, you instantiate the form object, which in turn instantiates its control objects. You could load a second instance of the form, which in turn would instantiate a new instance of the form and new instances of all controls. You would then have two forms in memory and two of each used control.

To instantiate an object in code, you create a variable that holds a reference to an instantiated object. You then manipulate the variable as an object. The statement you wrote in step 2 creates a new variable called objGraphics, which holds a reference to an object of type Graphics from the .NET Framework System.Drawing class. You also initialized the value for objGraphics to null. You learn more about variables in [Hour 12], "Using Constants, Data Types, Variables, and Arrays."

  1. Enter the second line of code exactly as shown here:
objGraphics = CreateGraphics();

CreateGraphics is a method of the form. The CreateGraphics method is pretty complicated under the hood, and I discuss it in detail in [Hour 10]. For now, understand that the method CreateGraphics instantiates a new object that represents the client area of the current form. The client area is the gray area within the borders and title bar of a form. Anything drawn onto the objGraphics object appears on the form. What you've done is set the variable objGraphics to point to an object that was returned by the CreateGraphics method. Notice how values returned by a property or method don't have to be traditional values such as numbers or text; they can also be objects.

  1. Enter the third line of code as shown next:
objGraphics.Clear(System.Drawing.SystemColors.Control);

This statement clears the background of the form using whatever color the user has selected as the Windows forms color.

How does this happen? In step 3, you used the CreateGraphics method of the form to instantiate a new graphics object in the variable objGraphics. With the code statement you just entered, you're calling the clear method of the objGraphics object. The Clear method is a method of all Graphics objects used to clear the graphics surface. The Clear method accepts a single parameter�the color to which you want the surface cleared.

The value you're passing to the parameter looks fairly convoluted. Remember that "dots" are a method of separating objects from their properties and methods.

Knowing this, you can discern that System is an object (technically it's a Namespace, as discussed in [Hour 24], "The 10,000-Foot View," but for our purposes it behaves just like an object) because it appears before any of the dots. However, there are multiple dots. What this means is that Drawing is an object property of the System object; it's a property that returns an object. So the dot following Drawing is used to access a member of the Drawing object, which in turn is a property of the System object. We're not done yet, however, because there is yet another dot. Again, this indicates that SystemColors, which follows a dot, is an object of the Drawing object, which in turn is…well, you get the idea. As you can see, object references can and do go pretty deep, and you'll use many dots throughout your code. The key points to remember are the following:

    • Text that appears to the left of a dot is always an object (or Namespace).
    • Text that appears to the right of a dot is a property reference or a method call.
    • Methods are never objects. In addition, methods are always followed by parentheses. If the text in question isn't followed by parentheses, it's definitely a property. Therefore, text that appears between two dots is a property that returns an object. Such a property is called an object property.

The final text in this statement is the word Control. Because Control is not followed by a dot, you know that it's not an object; therefore, it must be a property or a method. Because you expect this string of object references to return a color value to be used to clear the Graphics object, you know that Control must be a property or a method that returns a value. A quick check of the documentation (or simply realizing that the text isn't followed by a set of parentheses) would tell you that Control is indeed a property. The value of Control always equates to the color designated on the user's computer for the face of forms. By default, this is a light gray (often fondly referred to as battleship gray), but users can change this value on their computers. By using this property to specify a color rather than supplying the actual value for gray, you are assured that no matter the color scheme used on a computer, the code will clear the form to the proper system color. System colors are explained in [Hour 10].

  1. Enter the following statement:
objGraphics.DrawLine(System.Drawing.Pens.Chartreuse, 0, 0,
 this.DisplayRectangle.Width, this.DisplayRectangle.Height);

This statement draws a chartreuse line on the form. Within this statement is a single method call and three property references. Can you tell what's what? Immediately following objGraphics (and a dot) is DrawLine. Because no equal sign is present (and the text is followed by parentheses), you can deduce that this is a method call. As with the Clear() method, the parentheses after DrawLine() are used to enclose a value passed to the method. The DrawLine() method accepts the following parameters in the order in which they appear here:

    • A Pen
    • X value of first coordinate
    • Y value of first coordinate
    • X value of second coordinate
    • Y value of second coordinate

The DrawLine() method draws a straight line between coordinate one and coordinate two, using the pen specified in the Pen parameter. I'm not going to go into detail on pens here (refer to [Hour 10]), but suffice it to say that a pen has characteristics such as width and color. Looking at the dots once more, notice that you're passing the Chartreuse property of the Pens object. Chartreuse is an object property that returns a predefined Pen object that has a width of 1 pixel and the color chartreuse.

You're passing 0 as the next two parameters. The coordinates used for drawing are defined such that 0,0 is always the upper-left corner of a surface. As you move to the right of the surface, X increases, and as you move down the surface, Y increases; you can use negative values to indicate coordinates that appear to the left or above the surface. The coordinate 0,0 causes the line to be drawn from the upper-left corner of the form's client area.

The object property DisplayRectangle is referenced twice in this statement. DisplayRectangle is a property of the form that holds information about the client area of the form. Here, you're simply getting the Width and Height properties of the client area and passing them to the DrawLine method. The result is that the end of the line will be at the lower-right corner of the form's client area.

  1. Last, you have to clean up after yourself by entering the following code statement:
objGraphics.Dispose();

Objects often make use of other objects and resources. The underlying mechanics of an object can be truly boggling and almost impossible to discuss in an entry-level programming book. The net effect, however, is that you must explicitly destroy most objects when you're done with them. If you don't destroy an object, it may persist in memory and it may hold references to other objects or resources that exist in memory. This means you can create a memory leak within your application that slowly (or rather quickly) munches system memory and resources. This is one of the cardinal no-no's of Windows programming, yet the nature of using resources and the fact you're responsible for telling your objects to clean up after themselves makes this easy to do.

Objects that must explicitly be told to clean up after themselves usually provide a Dispose method. When you're done with such an object, call Dispose on the object to make sure it frees any resources it might be holding.

For your convenience, following are all the lines of code:

System.Drawing.Graphics objGraphics = null;

objGraphics = CreateGraphics();
objGraphics.Clear(System.Drawing.SystemColors.Control);
objGraphics.DrawLine(System.Drawing.Pens.Chartreuse, 0, 0,
 this.DisplayRectangle.Width, this.DisplayRectangle.Height);
objGraphics.Dispose();
Testing Your Object Example Project 

Now the easy part. Run the project by pressing F5 or by clicking the Start button on the toolbar. Your form looks pretty much like it did at design time. Clicking the button causes a line to be drawn from the upper-left corner of the form's client area to the lower-right corner (see [Figure 3.7]).

Figure 3.7. Simple lines and complex drawings are accomplished using objects.


Book - Pencil
If you receive any errors when you attempt to run the project, go back and make sure the code you entered exactly matches the code I've provided.


Resize the form, larger or smaller, and click the button again. Notice that the form is cleared and a new line is drawn. If you were to omit the statement that invokes the Clear method (and you're welcome to stop your project and do so), the new line would be drawn, but any and all lines already drawn would remain.

Book - Pencil
If you use Alt+Tab to switch to another application after drawing one or more lines, the lines will be gone when you come back to your form. In [Hour 10], you'll learn why this is so and how to work around this behavior.


Stop the project now by clicking Stop Debugging on the C# toolbar and then click Save All to save your project. What I hope you've gained from building this example is not necessarily that you can now draw a line (which is cool), but rather an understanding of how objects are used in programming. As with learning almost anything, repetition aids in understanding. Therefore, you'll be working with objects a lot throughout this book.

>


Understanding Collections

A collection is just what its name implies: a collection of objects. Collections make it easy to work with large numbers of similar objects by enabling you to create code that performs iterative processing on items within the collection. Iterative processing is an operation that uses a loop to perform actions on multiple objects, rather than writing the operative code for each object. In addition to containing an indexed set of objects, collections also have properties and may have methods. [Figure 3.8] illustrates the structure of a collection.

Figure 3.8. Collections contain sets of like objects, and they have their own properties and methods.

graphics/03fig08.gof

Continuing with the Dog/Pet object metaphor, think about what an Animals collection might look like. The Animals collection could contain one or more Pet objects, or it could be empty (containing no objects). All collections have a Count property that returns the total count of objects contained within the collection. Collections may also have methods, such as a Delete method used to remove objects from the collection or an Add method used to add a new object to the collection.

To better understand collections, you're going to create a small C# project that cycles through the Controls collection of a form, telling you the value of the Name property of every control on the form.

To create your sample project, follow these steps:

  1. Start C# now (if it's not already loaded) and create a new Windows Application project titled Collections Example.
  2. Change the text of the form to Collections Example by using the Properties window.
  3. Add a new button to the form by double-clicking the Button tool in the toolbox. Set the button's properties as follows:
Property Value
Name btnShowNames
Location 88,112
Size 120,23
Text Show Control Names
  1. Next, add some text box and label controls to the form. As you add the controls to the form, be sure to give each control a unique name. Feel free to use any name you like, but you can't use spaces in a control name. You may want to drag the controls to different locations on the form so that they don't overlap.
  2. When you are finished adding controls to your form, double-click the Show Control Names button to add code to its Click event. Enter the following code:
for (int intIndex=0; intIndex < this.Controls.Count; intIndex++)
{
 MessageBox.Show ("Control # " + intIndex.ToString() +
 " has the name " + this.Controls[intIndex].Name);
}
Book - Pencil
Every form has a Controls collection, which may or may not contain any controls. Even if no controls are on the form, the form still has a Controls collection.


The first statement (the one that begins with for) accomplishes a few tasks. First, it initializes the variable intIndex to 0, and then tests the variable. It also starts a loop executing the statement block (loops are discussed in [Hour 15], "Looping for Efficiency"), incrementing intIndex by one until intIndex equals the number of controls on the form, less one. The reason that intIndex must always be less than the Count property is that when referencing items in a collection, the first item is always item zero�collections are zero based. Thus, the first item is in location zero, the second item is in location one, and so forth. If you tried to reference an item of a collection in the location of the value of the Count property, an error would occur because you would be referencing an index that is one higher than the actual locations within the collection.

The MessageBox.Show() method (discussed in detail in [Hour 18], "Interacting with Users ") is a class available in the .NET Framework that is used to display a simple dialog box with text. The text that you are providing, which the MessageBox.Show() method will display, is a concatenation of multiple strings of text. (Concatenation is the process of adding strings together; it is discussed in [Hour 13], "Performing Arithmetic, String Manipulation, and Date/Time Adjustments.")

Run the project by pressing F5 or by clicking Start on the toolbar. Ignore the additional controls that you placed on the form and click the Show Control Names button. Your program will then display a message box similar to the one shown in [Figure 3.9] for each control on your form (because of the loop). When the program is finished displaying the names of the controls, choose Stop Debugging from the Debug toolbar to stop the program, and then save the project.

Figure 3.9. The Controls collection enables you to get to each and every control on a form.


Because everything in C# is an object, you can expect to use numerous collections as you create your programs. Collections are powerful, and the quicker you become comfortable using them, the more productive you'll become.

>


Using the Object Browser

C# includes a useful tool that lets you easily view members, such as properties and methods, of all the objects in a project: the Object Browser (see [Figure 3.10]). This is extremely useful when dealing with objects that aren't well documented, because it enables you to see all the members an object supports. To view the Object Browser, display the Other Windows submenu of the View menu and choose Object Browser.

Figure 3.10. The Object Browser lets you view all properties and methods of an object.

The Browse drop-down list in the upper-left corner of the Object Browser is used to determine the browsing scope. You can choose Active Project to view only the objects referenced in the active project, or you can choose Selected Components (the default) to view a set of selected objects. The Object Browser shows a preselected set of objects for Selected Components, but you can customize the object set by clicking the Customize button next to the Browse drop-down list. I wouldn't recommend changing the custom object set until you have some experience using C# objects and some experience using the Object Browser, as well.

The top-level nodes in the Objects tree are libraries. Libraries are usually DLL or EXE files on your computer that contain one or more objects. To view the objects within a library, simply expand the library node. As you select objects within a library, the list to the right of the Objects tree will show information regarding the members of the selected object (refer to [Figure 3.10]). For even more detailed information, click a member in the list on the right, and the Object Browser will show information about the member in the gray area below the two lists.

Summary

[wax ka badal]

In this hour, you learned all about objects. You learned how objects have properties, which are attributes that describe the object. Some properties can be set at design time using the Properties window, and most can also be set at runtime in C# code. You learned that referencing a property on the left side of the equal sign has the effect of changing a property, whereas referencing a property on the right side of the equal sign retrieves the property's value.

In addition to properties, you learned that objects have executable functions, called methods. Like properties, methods are referenced by using a "dot" at the end of an object reference. An object may contain many methods and properties, and some properties can even be objects themselves. You learned how to "follow the dots" to interpret a lengthy object reference.

Objects are often used as a group, called a collection. You learned that a collection often contains properties and methods, and that collections let you easily iterate through a set of like objects. Finally, you learned that the Object Browser can be used to explore all the members of an object in a project.

The knowledge you've gained in this hour is fundamental to understanding programming with C#, because objects and collections are the basis on which applications are built. After you have a strong grasp of objects and collections�and you will have by the time you've completed all the hours in this book�you'll be well on your way to fully understanding the complexities of creating robust applications using C#.

Q1: Is there an easy way to get help about an object's member?
A1: Absolutely. C#'s context-sensitive Help extends to code as well as to visual objects. To get help on a member, write a code statement that includes the member (it doesn't have to be a complete statement), position the cursor within the member text, and press F1. For instance, to get help on the Count property of the controls collection, you could type this.Controls.Count, position the cursor within the word Count, and press F1.
Q2: Are there any other types of object members besides properties and methods?
A2: Yes. An event is actually a member of an object, although it's not always thought of that way. Not all objects support events, however, but most objects do support properties and methods.


Workshop

[wax ka badal]

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 [Appendix A], "Answers to Quizzes/Exercises."

[ 1: True or False: C# is a true object-oriented language.
[ 2: An attribute that defines the state of an object is called a what?
[ 3: To change the value of a property, the property must be referenced on which side of an equal sign?
[ 4: What is the term for when a new object is created from a template?
[ 5: An external function of an object (one that is available to code using an object) is called a what?
[ 6: True or False: A property of an object can be another object.
[ 7: A group of like objects is called what?
[ 8: What tool is used to explore the members of an object?


Exercises
  1. Create a new project and add text boxes and a button to the form. Write code that, when clicked, places the text in the first text box into the second text box. Hint: Use the Text property of the text box controls.
  2. Modify the collections example in this hour to print the Height of all controls, rather than the name.
[.htm [ch04.htm [03.htm#toppage Top]


Hour 4. Understanding Events

[wax ka badal]

It's fairly easy to create an attractive interface for an application using C#'s integrated design tools. You can create beautiful forms that have buttons to click, text boxes in which to type information, picture boxes in which to view pictures, and many other creative and attractive elements with which users can interact. However, this is just the start of producing a C# program. In addition to designing an interface, you have to empower your program to perform actions in response to how a user interacts with the program and how Windows interacts with the program. This is accomplished by using events. In the previous hour, you learned about objects and their members�notably, properties and methods. In this hour, you'll learn about object events and event-driven programming, and you'll learn how to use events to make your applications responsive.

The highlights of this hour include the following:

  • Understanding event-driven programming
  • Triggering events
  • Avoiding recursive events
  • Accessing an object's events
  • Working with event parameters
  • Creating event handlers
  • Dealing with orphaned events

Understanding Event-Driven Programming

[wax ka badal]

With "traditional" programming languages (often referred to as procedural languages), the program itself fully dictates what code is executed and when it's executed. When you start such a program, the first line of code in the program executes, and the code continues to execute in a completely predetermined path. The execution of code may, on occasion, branch and loop, but the execution path is completely controlled by the program. This often meant that a program was rather restricted in how it could respond to the user. For instance, the program might expect text to be entered into controls on the screen in a predetermined order, unlike in Windows, where a user can interact with different parts of the interface, often in any order the user chooses.

New term
C# incorporates an event-driven programming model. Event-driven applications aren't bound by the constraints of procedural programs. Instead of the top-down approach of procedural languages, event-driven programs have logical sections of code placed within events. There is no predetermined order in which events occur, and often the user has complete control over what code is executed in an event-driven program by interactively triggering specific events, such as by clicking a button. An event, along with the code it contains, is called an event procedure.


Triggering Events 

In the previous hour, you learned how a method is simply a function of an object. Events are a special kind of method; they are a way for objects to signal state changes that may be useful to clients of that object. Events are methods that can be called in special ways�usually by the user interacting with something on a form or by Windows itself, rather than being called from a statement in your code.

There are many types of events and many ways to trigger those events. You've already seen how a user can trigger the Click event of a button by clicking it. User interaction isn't the only thing that can trigger an event, however. An event can be triggered in one of the following four ways:

  • Users can trigger events by interacting with your program.
  • Objects can trigger their own events, as needed.
  • The operating system (whichever version of Windows the user is running) can trigger events.
  • You can trigger events by calling them using C# code.
Events Triggered Through User Interaction 

The most common way an event is triggered is by a user interacting with a program. Every form, and almost every control you can place on a form, has a set of events specific to its object type. For example, the Button control has a number of events, including the Click event, which you've already used in previous hours. The Click event is triggered, and then the code within the Click event executes when the user clicks the button.

The Textbox control allows users to enter information using the keyboard, and it also has a set of events. The Textbox control has some of the same types of events as the Button control, such as a Click event, but the Textbox control also has events not supported by the Button control, such as a TextChanged event. The TextChanged event occurs each time the contents of the text box change, such as when the user types information into the text box. Because you can't enter text within a Button control, it makes sense that the Button control wouldn't have a TextChanged event. Each and every object that supports events supports a unique set of events.

Each type of event has its own behavior, and it's important to understand the events with which you work. The TextChanged event, for instance, exhibits a behavior that may not be intuitive to a new developer because the event fires each time the contents of the text box change. If you were to type the following sentence into an empty text box:

C# is very cool!

the Change event would be triggered 16 times�once for each character typed�because each time you enter a new character, the contents of the text box are changed. Although it's easy to think that the Change event fires only when you commit your entry, such as by leaving the text box or pressing Enter, this is simply not how it works. Again, it's important to learn the nuances and the exact behavior of the events you're using. If you use events without fully understanding how they work, your program may exhibit unusual, and often very undesirable, results.

Book - Pencil
Triggering events (which are just a type of procedure) using C# code is discussed in detail in [Hour 11], "Creating and Calling Methods."


Events Triggered by an Object 

Sometimes an object triggers its own events. The most common example of this is the Timer control's Timer event. The Timer control doesn't appear on a form when the program is running; it appears only when you're designing a form. The Timer control's sole purpose is to trigger its Timer event at an interval that is specified in its Interval property.

By setting the Timer control's Interval property, you control the interval, in milliseconds, when the Timer event executes. After firing its Timer event, a Timer control resets itself and again fires its Timer event when the interval has passed. This occurs until the interval is changed, the Timer control is disabled, or the Timer control's form is unloaded. A common use of timers is to create a clock on a form. You can display the time in a label and update the time at regular intervals by placing the code to display the current time in the Timer event. You'll create a project with a Timer control in [Hour 8], "Advanced Controls."

Events Triggered by the Operating System

[wax ka badal]

Finally, Windows can trigger certain events within your program �events that you may not even know exist. For example, when a form is fully or partially obstructed by another window, the program needs to know when the offending window is resized or moved so that it can repaint the area of its window that's been hidden. Windows and C# work together in this respect. When the obstructing window is moved or resized, Windows tells C# to repaint the form, which C.htm# does. This also causes C# to raise the form's Paint event. You can place code into the Paint event to create a custom display for the form, such as drawing shapes on the form using a Graphics object. That way, every time the form repaints itself, your custom drawing code executes.

Avoiding Recursive Events

[wax ka badal]
New term
You must make sure never to cause an event to endlessly trigger itself. An event that continuously triggers itself is called a recursive event. To illustrate a situation that causes a recursive event, think of the text box's TextChanged event discussed earlier. The TextChanged event fires every time the text within the text box changes. Placing code into the TextChanged event that alters the text within the text box would cause the Change event to be fired again, which could result in an endless loop. Recursive events terminate when Windows returns a StackOverFlow exception (see [Figure 4.1]), indicating that Windows no longer has the resources to follow the recursion.


Figure 4.1. Recursive events eventually exhaust Windows's resources until an exception (error) occurs.

graphics/04fig01.gof

Bulb
When you receive a StackOverFlow exception, you should look for a recursive event as the culprit.


Recursive events can involve more than one event in the loop. For example, if Event A triggers Event B, which in turn triggers Event A, you can have recursion of the two events. Recursion can take place among a sequence of many events, not just one or two.

Book - Pencil
Uses for recursive procedures actually exist, such as when you are writing complex math functions. For instance, recursive events are often used to compute factorials. However, when you purposely create a recursive event, you must ensure that the recursion isn't infinite.


Accessing an Object's Events 

Accessing an object's events is simple, and if you've been following the examples in this book, you've already accessed a number of objects' default events. To access all of an object's events, you can use the Events icon (the lightning bolt) in the Properties window.

You're now going to create a project to get the feel for working with events. Start C# and create a new Windows Application project titled View Events, and then follow these steps:

  1. Use the toolbox to add a picture box to the form.
  2. Change the name of the picture box to picText.
  3. Click the Events button on the Properties window toolbar (the lightning bolt icon).

Your screen should look like the one in [Figure 4.2]. Notice that the Properties window now lists all the events for the selected object; in your case, it is the picText PictureBox object.

Figure 4.2. Double�click an event in the Properties window to create the desired event.

When you access a control's events, the default event for that type of control is selected. As you can see, the Click event is the default for a PictureBox. Scroll through the picText events and select the MouseDown event. Double-click the word MouseDown and C# will create the MouseDown event procedure and position you within it, ready to enter code (see [Figure 4.3]).

Figure 4.3. C# creates an empty event procedure when you select an object's event for the first time.

New term
The code statement above the cursor is the event declaration. An event declaration is a statement that defines the structure of an event handler. Notice that this event declaration contains the name of the object, an underscore character (_), and then the event name. Following the event name is a set of parentheses. The items within the parentheses are called parameters, which is the topic of the next section. This is the standard declaration structure for an event procedure.


The full event declaration for the Click event is the following:

private void picText_MouseDown(object sender, _
 System.Windows.Forms.MouseEventArgs e)
Book - Pencil
The words Private and Void are reserved words that indicate the scope and type of the method. Scope and type are discussed in [Hour 11].


Working with Event Parameters
New term
As mentioned previously, the items within the parentheses of an event declaration are called parameters. An event parameter is a variable that is created and assigned a value by C#. These parameter variables are used to get, and sometimes set, relevant information within the event. Multiple parameters within an event procedure are always separated by commas. A parameter contains data that relates to the event. This data may be a number, text, an object�almost anything. As you can see, the MouseDown event has two parameters. When the Click event procedure is triggered, C# automatically creates the parameter variables and assigns them values for use in this one execution of the event procedure; the next time the event procedure occurs, the values in the parameters are reset. You use the values in the parameters to make decisions or perform operations in your code.


The MouseDown event of a form has the following parameters:

object sender

and

System.Windows.Forms.MouseEventArgs e

The first word identifies the type of data the parameter contains, followed by the name of the parameter. The first parameter, sender, holds a generic object. Object parameters can be any type of object supported by C#. It's not critical that you understand data types right now, just that you're aware that different parameter variables contain different types of information. Some contain text, others contain numbers, and still others (many others) contain objects. In the case of the sender parameter, it will always hold a reference to the control causing the event.

New term
The sender parameter returns a reference to the control that causes the event. It's often best to use the sender parameter rather than referencing the control by name, so that if you change the name of the control, you won't have to update the code. Also, by referencing the sender object, the code becomes portable; you can copy and paste it into the event of a different control of the same type, and the code should work without modification.


The e parameter, on the other hand, is where the real action is with the MouseDown event. The e parameter also holds an object; in this case the object is of the type System.WinForms.MouseEventArgs. This object has properties that relate to the MouseDown_event. To see them, type in the following code, but don't press anything after entering the dot (period):

e.

When you press the period, you'll get a drop-down list showing you the members (properties and methods) of the e object (see [Figure 4.4]). Using the e object, you can determine a number of things about the occurrence of the MouseDown event. I've listed some of the more interesting items in [04.htm#ch04table01 Table 4.1].

Figure 4.4. IntelliSense drop-down lists alleviate the need for memorizing the makeup of hundreds of objects.

Property Description
Clicks Returns the number of times the user clicked the mouse button.
Button Returns the button that was clicked (left, middle, right).
X Returns the horizontal coordinate at which the pointer was located when the user clicked.
Y Returns the vertical coordinate at which the pointer was located when the user clicked.


Book - Pencil
Each time the event occurs, the parameters are initialized by C# so that they always reflect the current occurrence of the event.


Each event has parameters specific to it. For instance, the TextChanged event returns parameters different from the MouseDown event. As you work with events�and you'll work with a lot of events�you'll quickly become familiar with the parameters of each event type. You'll learn how to create parameters for your own methods in [Hour 11].

Deleting an Event Handler

[wax ka badal]

Deleting an event handler involves more than just deleting the event procedure. When you add a new event handler to a class, C# automatically creates the event procedure for you and positions you to enter code within the event. However, C# does a little bit more for you "under the covers" to hook the event procedure to the control. It does this by creating a code statement in the hidden code of the class. Ordinarily, you don't have to worry about this statement. However, when you delete an event procedure, C# doesn't automatically delete the hidden code statement, and your code won't compile. The easiest way to correct this is to run the project; when C# encounters the error, it will show you the offending statement, which you can delete. Try this now:

  1. Delete the MouseDown procedure (don't forget to delete the open and close brackets of the procedure, as well as any code within them). This deletes the procedure.
  2. Press F5 to run the project. You'll receive a message that a build error has occurred. Click No to return to the code editor.
  3. A task for the error has been created in the Task List. Double-click the task and C# will take you to the offending statement. It will read:
this.pictureBox1.MouseDown += new
 System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseDown);
  1. Delete this statement, and now your code will compile and run.

Whenever you delete an event procedure, you will have to delete the corresponding statement that links the procedure to its object before the code will run.

Building an Event Example Project 

You're now going to create a very simple project in which you'll use the event procedures of a text box. Specifically, you're going to write code to display a message when a user presses a mouse button on the text box, and you'll write code to clear the text box when the user releases the button. You'll be using the e parameter to determine which button the user has pressed.

Creating the User Interface

[wax ka badal]

Create a new Windows application titled Events Example. Change the form's Text property to Events Demo.

Next, add a text box to the form by double-clicking the TextBox tool in the toolbox. Set the properties of the text box as follows:

Property Value
Name txtEvents
Location 48,120
Size 193,20
Text Click Me!

The only other control you need on your form is a label. Label controls are used to display static text; users cannot type text into a label. Add a new label to your form now by double-clicking the Label tool in the toolbox and then setting the Label control's properties as follows:

Property Value
Name lblMessage
Location 48,152
Size 192,16
Text (make blank)
TextAlign MiddleCenter

Your form should now look like the one in [Figure 4.5]. It's a good idea to save frequently, so save your project now by clicking the Save All button on the toolbar.

Figure 4.5. A Label control that has no value in its Text property can be hard to see unless selected.

Creating Event Handlers

[wax ka badal]

The interface for the Events Example project is complete�on to the fun part. You're now going to create the event procedures that empower your program to do something. The event that we're interested in first is the MouseDown event. Select the TextBox on your design form, and then click the Events icon on the Properties window toolbar.

The default event for text boxes is the TextChanged event, so it's the one now selected. You're not interested in the TextChanged event at this time, however. Scroll through the event list for the MouseDown event. Double-click MouseDown; C# then creates a new MouseDown event procedure for the text box (see [Figure 4.6]).

.

Enter the following code into the MouseDown event procedure:

switch(e.Button)
{
 case MouseButtons.Left:
 lblMessage.Text = "You are pressing the left button!";
 break;
 case MouseButtons.Right:
 lblMessage.Text = "You are pressing the right button!";
 break;
 case MouseButtons.Middle:
 lblMessage.Text = "You are pressing the middle button!";
 break;
}

The Switch construct, which is discussed in detail in [Hour 14], "Making Decisions in C# Code," compares the value of an expression to a list of possible values. In this instance, the expression is the value of e.Button (the Button property of the object e). When this code executes, the expression is compared to each Case statement in the order in which the statements appear. If and when a match is found, the code immediately following the Case statement that was matched gets executed. Therefore, the code you wrote looks at the value of e.Button and compares it to three values, one at a time. When the Switch construct determines which button has been pressed, it displays a message about it in the Label control.

Book - Pencil
In a more robust application, you would probably perform more useful and more complicated code. For instance, you may want to display a custom pop-up menu when the user clicks with the right button and execute a specific function when the user clicks with the middle button. All this is possible, and more.


The nice thing about objects is that you don't have to commit every detail about them to memory. For example, you don't need to memorize the return values for each type of button (who wants to remember MouseButtons.Left anyway?). Just remember that the e parameter contains information about the event. When you type e and press the period, the IntelliSense drop-down list appears and shows you the members of e, one of which is Button.

Don't feel overwhelmed by all the object references you'll encounter throughout this book. Simply accept that you can't memorize them all, nor do you need to; you'll learn the ones that are important, and you'll use Help when you're stuck. Also, after you know the parent object in a situation, such as the e object in this example, it's easy for you to determine the objects and members that belong to it by using the IntelliSense drop-down lists.

You're now going to add code to the MouseUp event to clear the label's Text property when the user releases the button. First, you'll need to create the MouseUp event procedure. To do this, return to the Form Design view (click the Form1.cs[Design] tab). The Properties should still have the txtEvents object's events listed. If the events aren't shown in the Properties window, select txtEvents from the drop-down list box in the Properties window and click the events icon. Locate and double-click the MouseUp event from the events list.

All you're going to do in the MouseUp_event is clear the label. Enter the following code:

lblMessage.Text = "";
===Testing Your Events Project===

Run your project now by pressing F5. If you entered all the code correctly and you don't receive any errors, your form will be displayed as shown in [Figure 4.7].

Figure 4.7. A simple but functional example.


Book - Pencil
Remember that C# is case sensitive. Entering only one character in the wrong case will cause your project to fail to compile.


Click the text box with the left mouse button and watch the label. It will display a sentence telling you which button has been clicked. When you release the button, the text is cleared. Try this with the middle and right buttons, as well. When you click the text box with the right button, Windows displays the standard shortcut menu for text boxes. When this menu appears, you have to select something from it or click somewhere off the menu to trigger the MouseUp event. In [Hour 9], "Adding Menus and Toolbars to Forms," you'll learn how to add your own shortcut menus to forms and controls. When you're satisfied that your project is behaving as it should, from the Debug menu choose Stop Debugging to stop the project (or click the Close button on your form), and then save your work by clicking Save All on the toolbar.

Summary

[wax ka badal]

In this hour, you learned about event-driven programming, including what events are, how to trigger events, and how to avoid recursive events. In addition, you've learned how to access an object's events and how to work with parameters. Much of the code you'll write will execute in response to an event of some kind. By understanding how events work, including being aware of the available events and their parameters, you'll be able to create complex C# programs that react to a multitude of user and system input.

Q1: Is it possible to create custom events for an object?
A1: You can create custom events for objects created from your custom classes (see [Hour 17], "Designing Objects with Classes"), but you cannot create custom events for existing C# objects such as forms and controls (without using some seriously advanced object-oriented techniques that are beyond the scope of this book).
Q2: Is it possible for objects that don't have an interface to support events?
A2: Yes. However, to use the events of such an object, the object variable must be dimensioned a special way or the events aren't available. This gets a little tricky and is beyond the scope of this book. If you have an object in code that supports events, look in Help for the keyword WithEvents for information on how to use such events. >


Workshop

[wax ka badal]

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 [Appendix A],"Answers to Quizzes/Exercises."

[ 1: Name three things that can cause events to occur.
[ 2: True or False: All objects support the same set of events.
[ 3: What is the default event type for a button?
[ 4: The act of an event calling itself in a loop is called what?
[ 5: What is the easiest way to access a control's default event handler?
[ 6: All control events pass a reference to the control causing the event. What is the name of the parameter that holds this reference?


Exercises
  1. Create a project with a single text box. In the Resize event of the form, show the Width of the form in the text box.
  2. Create a project with a form and a text box. Add code to the TextChange event to cause a recursion when the user types in text. Hint: Concatenate a character to the end of the user's text using a statement such as txtMyTextBox.Text = String. Concat(this. txtMyTextBox.Text,"a");
[.htm [part02.htm [04.htm#toppage Top]