User:Foxall/1
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:
- In the Properties window, click the Icon property to select it.
- When you click the Icon property, a small button with three dots appears to the right of the property. Click this button.
- 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)!
Q&A
[wax ka badal]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."
Quiz
[wax ka badal]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]- 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.)
- 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.
Navigating and Customizing the C# Environment
[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:
- 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.
- 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.
- 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:
- From the Toolbars tab of the Customize dialog box, click New.
- Enter My Help as the name for your new toolbar when prompted.
- 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:
- Locate and select the category Help. All the available commands for the Help category will appear in the list on the right.
- 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.
- 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:
- Start by creating a new Windows Application project. Name this project Changing Properties.
- 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.
- Select the Name property in the Properties window by clicking it, and then type in a name for the text box�call it txtComments.
- 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.
- 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.")
- 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:
- Locate the Picture Viewer program you created in the Quick Tour by choosing File, Open, and then clicking Project.
- 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.
- 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!
Q&A
[wax ka badal][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." Quiz[wax ka badal]
|