User:Foxall/01

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 [ch22.htm#ch22 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.


|- | graphics/newterm.gif | 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.


| align="right" | [ch01.htm Previous Section] [ch01lev1sec2.htm Next Section] |}


| align="right" | [01.htm#toppage Top] |}

./ ADD NAME=CH01LEV1SEC02.HTM

| align="right" | [ch01lev1sec1.htm Previous Section] [ch01lev1sec3.htm Next Section] |}

 Creating a New Project 

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 [01.htm#ch01fig01 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 [01.htm#ch01fig02 Figure 1.2].

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

graphics/01fig01.jpg

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

graphics/01fig02.jpg

|- | graphics/bookpencil.gif | If you don't see the Visual Studio Start page, chances are that you've changed the default settings. [ch02.htm#ch02 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.

|- | graphics/bulb.gif | 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 [01.htm#ch01fig03 Figure 1.3]).

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

graphics/01fig03.jpg

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

|- | graphics/bookpencil.gif | 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 [ch22.htm#ch22 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. |}


| align="right" | [ch01lev1sec1.htm Previous Section] [ch01lev1sec3.htm Next Section] |}


| align="right" | [01.htm#toppage Top] |}

./ ADD NAME=CH01LEV1SEC03.HTM

| align="right" | [ch01lev1sec2.htm Previous Section] [ch01lev1sec4.htm Next Section] |}

 Understanding the C# Environment 

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 to [ch01lev1sec2.htm#ch01fig03 Figure 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 [ch02.htm#ch02 Hour 2], "Navigating C#."

|- | graphics/bulb.gif | 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.


| align="right" | [ch01lev1sec2.htm Previous Section] [ch01lev1sec4.htm Next Section] |}


| align="right" | [01.htm#toppage Top] |}

./ ADD NAME=CH01LEV1SEC04.HTM

| align="right" | [ch01lev1sec3.htm Previous Section] [ch01lev1sec5.htm Next Section] |}

 Changing the Characteristics of Objects 

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 ([ch03.htm#ch03 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.

|- | graphics/newterm.gif | 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. |}


| align="right" | [ch01lev1sec3.htm Previous Section] [ch01lev1sec5.htm Next Section] |}


| align="right" | [01.htm#toppage Top] |}

./ ADD NAME=CH01LEV1SEC05.HTM

| align="right" | [ch01lev1sec4.htm Previous Section] [ch01lev1sec6.htm Next Section] |}

 Naming Objects 

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

|- | graphics/bookpencil.gif | 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 [ch05.htm#ch05 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.

|- | graphics/bookpencil.gif | 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 [ch12.htm#ch12 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. |}


| align="right" | [ch01lev1sec4.htm Previous Section] [ch01lev1sec6.htm Next Section] |}


| align="right" | [01.htm#toppage Top] |}

./ ADD NAME=CH01LEV1SEC06.HTM

| align="right" | [ch01lev1sec5.htm Previous Section] [ch01lev1sec7.htm Next Section] |}

 Setting the Text Property of the Form 

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.


| align="right" | [ch01lev1sec5.htm Previous Section] [ch01lev1sec7.htm Next Section] |}


| align="right" | [01.htm#toppage Top] |}

./ ADD NAME=CH01LEV1SEC07.HTM

| align="right" | [ch01lev1sec6.htm Previous Section] [ch01lev1sec8.htm Next Section] |}

 Giving the Form an Icon 

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.

|- | graphics/bookpencil.gif | 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 [ch22.htm#ch22 Hour 22], you'll learn how to assign an icon to your distributable file.)


| align="right" | [ch01lev1sec6.htm Previous Section] [ch01lev1sec8.htm Next Section] |}


| align="right" | [01.htm#toppage Top] |}

./ ADD NAME=CH01LEV1SEC08.HTM

| align="right" | [ch01lev1sec7.htm Previous Section] [ch01lev1sec9.htm Next Section] |}

 Changing the Size of the Form 

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 [01.htm#ch01fig04 Figure 1.4]).

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

graphics/01fig04.jpg

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 [01.htm#ch01fig05 Figure 1.5].

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

graphics/01fig05.jpg

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


| align="right" | [ch01lev1sec7.htm Previous Section] [ch01lev1sec9.htm Next Section] |}


| align="right" | [01.htm#toppage Top] |}

./ ADD NAME=CH01LEV1SEC09.HTM

| align="right" | [ch01lev1sec8.htm Previous Section] [ch01lev1sec10.htm Next Section] |}

 Adding Controls to a Form

|- | graphics/newterm.gif | 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 [01.htm#ch01fig06 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.

graphics/01fig06.jpg

|- | graphics/bulb.gif | You can add a control to a form in three ways, and [ch05.htm#ch05 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.

|- | graphics/bookpencil.gif | Refer to [ch02.htm#ch02 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


| align="right" | [ch01lev1sec8.htm Previous Section] [ch01lev1sec10.htm Next Section] |}


| align="right" | [01.htm#toppage Top] |}

./ ADD NAME=CH01LEV1SEC10.HTM

| align="right" | [ch01lev1sec9.htm Previous Section] [ch01lev1sec11.htm Next Section] |}

 Designing an Interface 

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 

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 [01.htm#ch01fig07 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.

graphics/01fig07.jpg

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 [01.htm#ch01fig08 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.

graphics/01fig08.jpg


| align="right" | [ch01lev1sec9.htm Previous Section] [ch01lev1sec11.htm Next Section] |}


| align="right" | [01.htm#toppage Top] |}

./ ADD NAME=CH01LEV1SEC11.HTM

| align="right" | [ch01lev1sec10.htm Previous Section] [ch01lev1sec12.htm Next Section] |}

 Adding an Invisible Control to a Form

|- | graphics/newterm.gif | 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.

|- | graphics/bookpencil.gif | 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 [01.htm#ch01fig09 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.

graphics/01fig09.jpg

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.


| align="right" | [ch01lev1sec10.htm Previous Section] [ch01lev1sec12.htm Next Section] |}


| align="right" | [01.htm#toppage Top] |}

./ ADD NAME=CH01LEV1SEC12.HTM

| align="right" | [ch01lev1sec11.htm Previous Section] [ch01lev1sec13.htm Next Section] |}

 Coding an Interface 

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 [ch04.htm#ch04 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 

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 [01.htm#ch01fig10 Figure 1.10]).

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

graphics/01fig10.jpg

|- | graphics/newterm.gif | 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.

|- | graphics/bookpencil.gif | For more information on creating good comments, see [ch16.htm#ch16 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 [ch03.htm#ch03 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)
 {

|- | graphics/bookpencil.gif | 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.

|- | graphics/bulb.gif | 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 [ch10.htm#ch10 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 + ")");
}

|- | graphics/bookpencil.gif | C# is case sensitive! You must enter all code using the same case as shown in the text. |}

Checking Your Program Entry Point 

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 [01.htm#ch01fig11 Figure 1.11].

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

graphics/01fig11.jpg

 Terminating a Program Using Code 

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();

|- | graphics/bookpencil.gif | 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. |}


| align="right" | [ch01lev1sec11.htm Previous Section] [ch01lev1sec13.htm Next Section] |}


| align="right" | [01.htm#toppage Top] |}

./ ADD NAME=CH01LEV1SEC13.HTM

| align="right" | [ch01lev1sec12.htm Previous Section] [ch01lev1sec14.htm Next Section] |}

 Running a Project 

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 [01.htm#ch01fig12 Figure 1.12]).

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

graphics/01fig12.jpg

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 [01.htm#ch01fig13 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 [01.htm#ch01fig14 Figure 1.14].

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

graphics/01fig13.jpg

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

graphics/01fig14.jpg


| align="right" | [ch01lev1sec12.htm Previous Section] [ch01lev1sec14.htm Next Section] |}


| align="right" | [01.htm#toppage Top] |}

./ ADD NAME=CH01LEV1SEC14.HTM

| align="right" | [ch01lev1sec13.htm Previous Section] [ch01lev1sec15.htm Next Section] |}

 Summary 

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)!


| align="right" | [ch01lev1sec13.htm Previous Section] [ch01lev1sec15.htm Next Section] |}


| align="right" | [01.htm#toppage Top] |}

./ ADD NAME=CH01LEV1SEC15.HTM

| align="right" | [ch01lev1sec14.htm Previous Section] [ch01lev1sec16.htm Next Section] |}

 Q&A
[01.htm#qad1e5122 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.
[01.htm#qad1e5146 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.


| align="right" | [ch01lev1sec14.htm Previous Section] [ch01lev1sec16.htm Next Section] |}


| align="right" | [01.htm#toppage Top] |}

./ ADD NAME=CH01LEV1SEC16.HTM

| align="right" | [ch01lev1sec15.htm Previous Section] [ch02.htm Next Section] |}

 Workshop 

The Workshop is designed to help you anticipate possible questions, review what you've learned, and get you thinking about how to put your knowledge into practice. The answers to the quiz are in [app01.htm#app01 Appendix A],"Answers to Quizzes/Exercises."

 Quiz
[app01lev1sec1.htm#ch01ans01 1:] What type of C# project creates a standard Windows program?
[app01lev1sec1.htm#ch01ans02 2:] What window is used to change the attributes (location, size, and so on) of a form or control?
[app01lev1sec1.htm#ch01ans03 3:] How do you access the default event (code) of a control?
[app01lev1sec1.htm#ch01ans04 4:] What property of a PictureBox do you set to display an image?
[app01lev1sec1.htm#ch01ans05 5:] What is the default event for a Button control?
Exercise
  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.


| align="right" | [ch01lev1sec15.htm Previous Section] [ch02.htm Next Section] |}


| align="right" | [01.htm#toppage Top] |}