a radically new approach: c# and windows m · pdf filewhen you examine this simple portion of...

34
1 C HAPTER 1 A Radically New Approach: C# and Windows Microsoft states that “C# is a simple, modern, object-oriented, and type-safe programming language derived from C and C++.” The first thing you will notice when using C# (C sharp) is how familiar you already are with many of the constructs of this language. Object-oriented by design, the C# language provides access to the class libraries available to Visual Basic and Visual C++ programmers. C#, however, does not provide its own class library. C# is implemented by Microsoft in the latest version of the Microsoft Visual Studio and provides access to the Next Generation Windows Services (NGWS). These services include a common execution engine for code development. Visual Studio .NET and C# The latest release of Microsoft’s Visual Studio .NET provides a language-rich environment for developing a variety of applications. Programming can be done in a variety of lan- guages, such as C, C++, C#, Visual Basic, and more. Applications can range from standal- one console (command-line or DOS mode) applications to Microsoft Windows programs. C#, although certainly one of the newest variations of C to hit the market, is just a component of this much larger package. One of Microsoft’s goals, in this release of the Visual Studio .NET, is to allow seamless solutions to project demands. Solutions to a task can include components from C++, Visual Basic, and C# all rolled into one seamless exe- cutable file. This book concentrates on the C# aspect of this package as it applies to creating Win- dows applications. If you are interested in a more detailed treatment of the C# language, we would recommend another of our books, C# Essentials, published by Prentice Hall (ISBN

Upload: lamlien

Post on 31-Jan-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

1

C

H A P T E R

1

A Radically New Approach:C# and Windows

M

icrosoft states that “C# is a simple, modern,object-oriented, and type-safe programming language derived from C and C++.” The firstthing you will notice when using C# (C sharp) is how familiar you already are with many ofthe constructs of this language. Object-oriented by design, the C# language provides accessto the class libraries available to Visual Basic and Visual C++ programmers. C#, however,does not provide its own class library.

C# is implemented by Microsoft in the latest version of the Microsoft Visual Studioand provides access to the Next Generation Windows Services (NGWS). These servicesinclude a common execution engine for code development.

Visual Studio .NET and C#

The latest release of Microsoft’s Visual Studio .NET provides a language-rich environmentfor developing a variety of applications. Programming can be done in a variety of lan-guages, such as C, C++, C#, Visual Basic, and more. Applications can range from standal-one console (command-line or DOS mode) applications to Microsoft Windows programs.

C#, although certainly one of the newest variations of C to hit the market, is just acomponent of this much larger package. One of Microsoft’s goals, in this release of theVisual Studio .NET, is to allow seamless

solutions

to project demands. Solutions to a taskcan include components from C++, Visual Basic, and C# all rolled into one seamless exe-cutable file.

This book concentrates on the C# aspect of this package as it applies to creating Win-dows applications. If you are interested in a more detailed treatment of the C# language, wewould recommend another of our books,

C# Essentials

, published by Prentice Hall (ISBN

Prentice Hall PTR
This is a sample chapter of C# for Windows Programming ISBN: 0-13-093287-6 For the full text, visit http://www.phptr.com ©2001 Pearson Education. All Rights Reserved.
Page 2: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

2 Chapter 1 • A Radically New Approach: C# and Windows

0-13-093285-X), 2002. This is just the book if you are the type of programmer who likes todiscover all of nuances of a language.

Our first task will be to learn how to use Visual Studio to create a simple C# consoleapplication. Then we’ll do a quick study of the most important aspects of the C# language.Finally, we’ll turn our attention to our first C# Windows application and see what is in storefor us in the remainder of this book.

Building C# Applications

C# applications fall within two distinct categories: command-line or console applicationsand Windows applications. By using the AppWizards, you’ll find that both are easy to cre-ate in terms of the template code necessary to outline a project.

For our first project we build the familiar Hello World console application. We’ll namethis project HelloWorld. The second application, which appears closer to the end of thischapter, is called CircleArea. This is a full-fledged, object-oriented Windows application.

Both projects are intended to introduce you to the Visual Studio AppWizards andshow you how to build the basic template code that will be part of every project developedin this book. These are good places to set bookmarks and take notes in the margins.

Your First C# Console Application

To build a console application using C#, start the Visual Studio. Select the File | New |Project sequence to open the New Project dialog box, as shown in Figure 1–1.

Page 3: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

Your First C# Console Application 3

Name this project HelloWorld, and specify a subdirectory under the root directory, asshown in Figure 1–1.

When you click the OK button, the C# AppWizard creates the template code shown inFigure 1–2.

Figure 1–1

The New Project dialog box allows us to specify a C# console application.

Page 4: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

4 Chapter 1 • A Radically New Approach: C# and Windows

This template code can now be modified to suite your purposes. Figure 1–3 showshow we altered the template code for our HelloWorld project.

Examine Figure 1–3 and compare it with the following complete listing. Note theaddition of just one line of code:

using System;

namespace HelloWorld{ /// <summary> /// Summary description for Class1. /// </summary> class Class1 { static void Main(string[] args) {

Figure 1–2

The AppWizard’s C# template code for a console application.

Page 5: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

Your First C# Console Application 5

// // TODO: Add code to start application here //

Console.WriteLine("Hello C# World!");

} }}

Examine Figure 1–3, once again. Notice that the Build menu has been opened and theRebuild option is about to be selected. Clicking this menu item will build the project.

Figure 1–3

The template code is altered for the HelloWorld project.

Page 6: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

6 Chapter 1 • A Radically New Approach: C# and Windows

When you examine this simple portion of code, you notice many of the elements thatyou are already familiar with from writing C or C++ console applications. Figure 1–4shows the Debug menu opened and the Start Without Debugging option about to beselected. Make this selection to run the application within the integrated environment of theVisual Studio.

When the program is executed, a console (command-line or DOS) window willappear with the programs output. Figure 1–5 shows the output for this application.

Now, let’s briefly examine the familiar elements and the new additions. First, theapplication uses the System directive. The System namespace, provided by the NGWS atruntime, permits access to the Console class used in the Main method. The use of Con-sole.WriteLine() is actually an abbreviated form of System.Console.WriteLine() whereSystem represents the namespace, Console a class defined within the namespace, andWriteLine() is a static method defined within the Console class.

Figure 1–4

Running the program from within Visual Studio.

Page 7: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

C# Programming Elements 7

Additional Program Details

In C# programs, functions and variables are always contained within class and structure def-initions and are never global.

You will probably notice the use of “.” as a separator in compound names. C# uses thisseparator is place of “::” and “->”. Also, C# does not need forward declarations because theorder in not important. The lack of #include statements is an indicator that the C# languagehandles dependencies symbolically. Another feature of C# is automatic memory manage-ment, which frees developers from dealing with this complicated problem.

C# Programming Elements

In the following sections we examine key elements of the C# language that we use through-out the book. From time to time, additional C# information is introduced, but the material inthe following sections is used repeatedly.

Figure 1–5

The console window shows the project’s output.

Page 8: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

8 Chapter 1 • A Radically New Approach: C# and Windows

Arrays

C# supports the same variety of arrays as C and C++, including both single and multidi-mensional arrays. This type of array is often referred to as a

rectangular array

, as opposedto a jagged array.

To declare a single-dimension integer array named

myarray

, the following C# syntaxcan be used:

int[] myarray = new int[12];

The array can then be initialized with 12 values using a

for

loop in the following man-ner:

for (int i = 0; i < myarray.Length; i++) myarray[i] = 2 * i;

The contents of the array can be written to the screen with a

for

loop and WriteLine()statement.

for (int i = 0; i < myarray.Length; i++) Console.WriteLine("myarray[{0}] = {1}", i, myarray[i]);

Note that

i

values will be substituted for the {0} and myarray[ ] values for {1} in theargument list provided with the WriteLine() statement.

Other array dimensions can follow the same pattern. For example, the syntax used forcreating a two-dimensional array can take this form:

int[,] my2array = new int[12, 2];

The array can then be initialized with values using two

for

loops in the followingmanner:

for (int i = 0; i < 12; i++) for (int j = 0; j < 2; j++) my2array[i, j] = 2 * i;

The contents of the array can then be displayed on the console with the following syn-tax:

for (int i = 0; i < 12; i++) for (int j = 0; j < 2; j++) Console.WriteLine("my2array[{0}, {1}] = {2}", i, j, my2array[i, j]);

Three-dimensional arrays can be handled with similar syntax using this form:

int[,,] my3array = new int[3, 6, 9];

Page 9: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

C# Programming Elements 9

In addition to handling multidimensional rectangular arrays, C# handles jaggedarrays. A jagged array can be declared using the following syntax:

int[][] jagarray1;

int[][][] jagarray2;

For example, suppose a jagged array is declared as:

int[][] jagarray1 = new int[2][];

jagarray1[0] = new int[] {2, 4};

jagarray1[1] = new int[] {2, 4, 6, 8};

Here jagarray1 represents an array of int. The jagged appearance of the structure givesrise to the array’s type name. The following line of code would print the value 6 to thescreen:

Console.WriteLine(jagarray1[1][2]);

For practice, try to write the code necessary to print each array element to the screen.

Attributes, Events, Indexers, Properties, and Versioning

Many of the terms in this section are employed when developing applications for Windows.If you have worked with Visual Basic or the Microsoft Foundation Class (MFC) and C++you are familiar with the terms

attributes, events,

and

properties

as they apply to controls. Inthe following sections, we generalize those definitions even more.

Attributes

C# attributes allow programmers to identify and program new kinds of declarative informa-tion. For example, public, private and protected are attributes that identify the accessibilityof a method.

An element’s attribute information can be returned at runtime using the NGWS runt-ime’s reflection support.

Events

Events are used to allow classes to provide notifications about which clients can provideexecutable code. This code is in the form of event handlers. Again, if you have developedMFC C++ Windows code, you are already familiar with event handlers.

Here is code for a button-click event handler, extracted from a project developed laterin this book:

Page 10: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

10 Chapter 1 • A Radically New Approach: C# and Windows

private void button1_Click(object sender, System.EventArgs e){ radius = Convert.ToDouble(textBox1.Text); textBox2.Text = (radius * radius * 22 / 7).ToString(); textBox3.Text = (radius * 2.0 * 22 / 7).ToString();}

The event handler contains code that will be executed when a button-click eventoccurs. The button is a button that resides on a form in a C# Windows application.

Indexers

Indexers are used by C# to expose array-like data structures, such as an array of strings. Thisdata structure might be used by a C# Windows control, such as a CheckedListBox control.

. . .{ private string[] items; public string this[int index] { get { return items[index]; } set { items[index] = value; Repaint(); }}

The CheckedListBox class can then be altered with the following code:

CheckedListBox MyListBox;MyListBox[0] = "List box title";Console.Write(MyListBox[0]);

The array-like access provided by indexers is similar to the field-like access providedby properties.

Properties

A property is an attribute that is associated with a class or object. Windows controls offer awide variety of changeable properties, including caption name, ID value, color, font, loca-tion, size, text, and so on.

Here is a small portion of a C# Windows program that modifies the properties of abutton control:

Page 11: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

C# Programming Elements 11

this.button1.Location = new System.Drawing.Point(152, 192);

this.button1.Size = new System.Drawing.Size(176, 24);

this.button1.TabIndex = 6;

this.button1.Text = "Push to Calculate";

this.button1.AddOnClick(new System.EventHandler(button1_Click));

Properties can be read or written to as the need arises.

Versioning

C# supports versioning by addressing two levels of compatibility. The first is source com-patibility, which occurs when code developed on an earlier version can be simply recom-piled to work on a later version.

The second type of compatibility is binary compatibility, which occurs when codedeveloped under an earlier version works under a newer version without recompiling.

Boxing, Unboxing, and the Unified Type System

All types in C# can be treated as objects. For example, the following line of code is accept-able in C#:

Console.WriteLine(12345.ToString());

In this case the ToString() method is used on the integer 12345 by treating it as anobject.

An object box can be used when a value is to be converted to a reference type. This iscalled

boxing

.

Unboxing

is used to convert a reference type back to a value. For example:

int num1 = 12345;

object myobject = num1; // boxed

int num2 = (int) myobject; // unboxed

Here the integer number, 12345, is first converted to a reference type with the use ofboxing, then converted from an object back to an integer value by casting the object(unboxing).

Classes, Structures, and Enum

C# provides simple, but unique, implementations to these common object-oriented features.

Page 12: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

12 Chapter 1 • A Radically New Approach: C# and Windows

Classes

C# classes allow only single inheritance. Members of a class can include constants, con-structors, destructors, events, indexers, methods, properties, and operators. Each membercan, in turn, have a public, protected, internal, protected internal, or private access.

The makeup of a class is similar to that used in C and C++. For example:

public class Form1 : System.Windows.Forms.Form{ // variable declaration public double radius = 7.5;

/// <summary> /// Required designer variable /// </summary> private System.ComponentModel.Container components; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox textBox1; . . .

In this example, the class itself is public and contains a variable with public access.The designer variables, however, use a private qualifier to limit access. Classes use a passby reference scheme as compared to a structures pass by value. For this reason, they tend tobe faster than the equivalent structure.

Structures

Structures, as in C and C++, are very similar to classes. As a matter of fact, they can be cre-ated with members similar to those described for classes. Structures differ from classes inthat they are value types with values being stored on the stack. This tends to make thenslower than an equivalent class because passing by value is slower than passing by reference.

Point

is typically used and implemented in C, C++, and C# as a structure:

struct Point{ public int x, y; public Point(int x, int y) { this.x = x; this.y = y; }}

This example illustrates the typical syntax for creating a structure.

Page 13: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

C# Programming Elements 13

Enum

The enum type declaration is used to provide a type name for a group of symbolic constantsthat are usually related to one another. For example:

enum vehicle {

Chrysler, Ford, GM

}

Use vehicle GM to access the GM element, and so on.

Namespaces

C# uses namespaces as an organization system applied both internally and externally. As aconvention, developers usually name namespaces after the company they are developingcode for.

The Visual C# AppWizard uses the following convention when creating a C# consolecode template:

using System;namespace Tester{ /// <summary> /// Summary description for Class1. /// </summary> class Class1 { static void Main(string[] args) { // // TODO: Add code to start application here // int[] myint = new int[] {1,2,3,4,5};

foreach (object o in myint) { Console.Write("the value of myint is: "); Console.WriteLine(o); } } }

}

We can modify that code to take on the following appearance:

Page 14: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

14 Chapter 1 • A Radically New Approach: C# and Windows

using System;

namespace Nineveh_National_Research.CSharp.Tester{ /// <summary> /// Summary description for ForEachDemo. /// </summary> class ForEachDemo { static void Main(string[] args) { // // TODO: Add code to start application here // int[] myint = new int[] {1,2,3,4,5};

foreach (object o in myint) { Console.Write("the value of myint is: "); Console.WriteLine(o); } } }

}

The namespace Nineveh_National_Research.CSharp.Tester is hierarchical. It reallymeans that there is a namespace Nineveh_National_Research that contains a namespacenamed CSharp that itself contains a namespace named Tester.

The

using

directive can be used as a shorthand notation instead of writing out thewhole namespace name. In the previous listing, the using directive allows all of the types inSystem to be used without qualification.

Predefined Types

In addition to the value and reference types discussed in the previous section, C# providesseveral predefined types.

For example, predefined value types include bool, byte, char, decimal, double, float,int, long, sbyte, short, uint, ulong and ushort. Table 1–1 lists and describes these types.

Table 1–1

C# Predefined Types

Type Description

bool Boolean type; true or false, 1 or 0

byte Unsigned 8-bit integer

Page 15: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

C# Programming Elements 15

The types listed in the first column Table 1–1 are abbreviated versions of a longerstructure name, but one preferred in C#.

Statements

Statement syntax in C# is basically the same as that for C and C++. In the following sec-tions you’ll see several familiar coding examples.

Blocks

C# allows blocking code so that one or more statements can be written in sequence. The fol-lowing portion of code shows several blocks:

// block 1Console.WriteLine("This is the first block");{ // block 2 Console.WriteLine("This is the second block"); {

char Unicode character

decimal 28-digit decimal type

double Double precision real

float Single precision real

int Signed 32-bit integer

long Signed 64-bit integer

object Base type for all other C# types

sbyte Signed 8-bit integer

short Signed 16-bit integer

string A sequence of Unicode characters

uint Unsigned 32-bit integer

ulong Unsigned 64-bit integer

ushort Unsigned 16-bit integer

Table 1–1

C# Predefined Types

(Continued)

Type Description

Page 16: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

16 Chapter 1 • A Radically New Approach: C# and Windows

// block 3

Console.WriteLine("This is the third block");

}

}

Any number of blocks can be created using this format.

Miscellaneous Statements

C# provides a number of miscellaneous statements that are listed and briefly explained inTable 1–2.

You are already familiar with a number of these statements from your work with Cand C++.

The do Statement

A

do

statement continues to execute a statement until the Boolean test is false. Here is asmall portion of code:

Table 1–2

C# Miscellaneous Statements

Statement Use

break For exiting an enclosing do, for, foreach, switch, or while statement.

checked Used to control the overflow checking context for arithmetic operations. All expressions are evaluated in a checked context.

continue For starting a new iteration of a do, for, foreach, switch, or while statement.

lock Used to obtain a mutual-exclusive lock for an object. With the lock in place, the statement will be executed then the lock will be released.

return Used to return control to the caller of the statement in which it appears.

throw Used to throw an exception.

try Used for catching exceptions while a block is executing.

unchecked Used to control the overflow checking context for arithmetic operations. All expressions are evaluated in an unchecked context.

Page 17: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

C# Programming Elements 17

int num1 = 0;

do { Console.WriteLine(num1); num1 += 2;}

while (num1 != 20);

The output from this code will be the numbers 0 to 18. Every

do

statement will beexecuted at least one time with the Boolean test being made after the statement.

The Expression Statement

An expression statement evaluates a given expression and discards any value calculated inthe process. Expressions such as (

x

+

s

), (

y

* 3), (

t

=2), and so on are not allowed as state-ments. The following is an example of an expression statement:

static int HereWeGo() {

Console.WriteLine("We made it to HereWeGo"); return 0;}

static void Main(string[] args){ // // TODO: Add code to start application here //

HereWeGo();

}

Once again, the value returned by HereWeGo() is discarded.

The for Statement

The

for

statement, like its C and C++ counterparts, initializes the expression, and then exe-cutes an expression when the Boolean test is true. For example:

for (int i = 0; i < 10; i++) {

Console.Write("the value of i is: "); Console.WriteLine(i);

}

This portion of code will report the value of i to the screen. The value of i incrementsfrom 0 to 9 before the Boolean condition is false.

Page 18: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

18 Chapter 1 • A Radically New Approach: C# and Windows

The foreach Statement

The foreach statement is used to enumerate the contents of a collection. For example:

int[] myint = new int[] {1,2,3,4,5};

foreach (object o in myint) { Console.Write("the value of myint is: "); Console.WriteLine(o);

}

In this collection, each integer element will be reported to the screen. The collection,in general, can be any type.

The if and if-else Statements

The if statement executes based on a Boolean decision. If the statement is true, the expres-sion will execute. If it is false, the statement will not execute. When used in conjunctionwith an else, the if-else combination will pass operation to the else when the if statement isfalse. For example:

int i = 2 * 23 / 12;

if ( i >= 5) Console.WriteLine("This is a big number");else

Console.WriteLine("This is a reasonable number");

This portion writes one message or another based on the calculated value of the inte-ger result.

The Label and goto Statements

The goto statement is used in conjunction with a label to transfer program control. Forexample:

goto C;

A: Console.WriteLine("This should be printed last");return 0;

B: Console.WriteLine("This should be printed second");goto A;

C: Console.WriteLine("This should be printed first");

goto B;

Page 19: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

C# Programming Elements 19

This concept is fairly straightforward. We recommend, however, limited use of gotostatements.

The switch (case-break) Statement

C# switch statements, like those of C and C++, execute statements that are associated withthe value of a particular expression. When no match occurs, a default condition is executed:

string str = "Top";

switch (str.Length) { case 0: Console.WriteLine("No characters in the string."); break; case 1: Console.WriteLine("One character in the string."); break; case 2: Console.WriteLine("Two characters in the string."); break; case 3: Console.WriteLine("Three characters in the string."); break; default: Console.WriteLine("A lot of characters in the string."); break;

}

A default option should always be provided in switch statements.

The while Statement

A while statement continues to execute while the Boolean result is true. For example:

int i = 5;

while (i <= 300) { i += 5; Console.WriteLine("Not there yet!");

}

The value of i is initialized to 5. When the final increment is made, the value in i willbe 305, and thus the loop will stop executing. The while statement continues to execute untilthe value of i is equal to or exceeds 300.

Page 20: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

20 Chapter 1 • A Radically New Approach: C# and Windows

Value and Reference Types

C# supports two main categories of types: value and reference types. You are already famil-iar with value types, including char, enum, float, int, struct, and so on. The key feature of thevalue type is that the variable actually contains the data

Reference types, on the other hand, include class, array, delegate, and interface types.An assignment to a reference type can affect other reference types derived from that refer-ence type.

Your First C# Windows ApplicationYou are about to discover that C# Windows applications are built in an atmosphere verysimilar to that of Visual Basic.

A C# Windows project is started in a manner similar to a console project except, ofcourse, the Windows option is selected. Start the Visual Studio and select the File | New |Project menu sequence to open the New Project dialog box, as shown in Figure 1–6.

Figure 1–6 The New Project dialog box for a C# Windows project.

Page 21: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

Your First C# Windows Application 21

Name this project CircleArea and set the subdirectory off of the root directory asshown in Figure 1–6.

Click Finish. The AppWizard creates the template code for the project and takes youto the design pane shown in Figure 1–7.

If you are familiar with Visual Basic, you will recognize this project design area. Whenyou build C# Windows applications, you’ll graphically design forms in this designer pane.

To create a working form that will eventually take on the appearance of a dialog boxwith controls, we need to view optional controls. We can see these controls by opening thetoolbox. To do this, use the View | Toolbox menu selection, as shown in Figure 1–8.

Figure 1–7 The default C# design pane for Windows projects.

Page 22: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

22 Chapter 1 • A Radically New Approach: C# and Windows

Optionally, you can select the toolbox with the Ctrl+Alt+X key sequence. When thetoolbox is selected, you see a variety of controls that can be used in your form design. Fig-ure 1–9 shows the toolbox and an altered form.

To produce the altered form, shown in Figure 1–9, place the mouse over a label con-trol in the toolbox. Hold down the left mouse button and drag the control to the form. Onceon the form, the control can be moved and sized to the position shown in Figure 1–9. In asimilar manner, move a button control from the toolbox to the form.

Figure 1–8 This option brings the toolbox to the design area.

Page 23: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

Your First C# Windows Application 23

Double-click the mouse on the button once it is sized and placed. This adds aButton1_Click method to the project’s code that we will alter shortly.

Now, we want to switch from the designer view to the code view to examine the tem-plate code written by the AppWizard. To switch to the code view, use the View | Code menusequence as shown in Figure 1–10.

Figure 1–9 An altered form with the toolbox in the left pane.

Page 24: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

24 Chapter 1 • A Radically New Approach: C# and Windows

Another option is to just press F7 when in the designer view to switch to the codeview. To switch from the code view back to the designer view requires just a Shift+F7 hotkey combination.

When you make the code view selection, you should see a project code listing very sim-ilar to the one in the following example. Note that several long lines of programming code arebroken and wrapped to the next line. This is necessary because of book page restrictions.

using System;using System.Drawing;using System.Collections;using System.ComponentModel;using System.Windows.Forms;using System.Data;

namespace CircleArea{

Figure 1–10 Use the Code menu option to view the AppWizard’s code.

Page 25: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

Your First C# Windows Application 25

/// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private System.Windows.Forms.Button button1; private System.Windows.Forms.Label label1;

public double radius = 12.3;

public Form1() { // // Required for Windows Form Designer support // InitializeComponent();

// // TODO: Add any constructor code after // InitializeComponent call // }

/// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); }

#region Windows Form Designer generated code /// <summary> /// Required method for Designer support – do /// not modify the contents of this method with

Page 26: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

26 Chapter 1 • A Radically New Approach: C# and Windows

/// the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel. Container(); this.Size = new System.Drawing.Size(296, 165); this.Text = "Form1"; this.label1 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); label1.Location = new System.Drawing. Point(40, 48); label1.Text = "label1"; label1.Size = new System.Drawing.Size(224, 24); label1.TabIndex = 0; button1.Location = new System.Drawing. Point(104, 104); button1.Size = new System.Drawing.Size(88, 32); button1.TabIndex = 2; button1.Text = "button1"; button1.Click += new System.EventHandler (this.button1_Click); this.AutoScaleBaseSize = new System.Drawing. Size(5, 13); this.Controls.Add (this.button1); this.Controls.Add (this.label1); } #endregion

/// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); }

private void button1_Click(object sender, System.EventArgs e) { label1.Text = (radius * radius * 22 / 7). ToString(); } }

}

Page 27: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

Your First C# Windows Application 27

All of the code you see, except for the code in boldface, was added by the AppWizardor the designer pane as you added various controls to the project. This is old news for VisualBasic programmers, but a startling surprise for C and C++ programmers!

Add the code shown in boldface in the previous listing. Now use the Build | Rebuildmenu selection to build the application. Use the Debug | Run Without Debugger menuoption to execute the program code. You should see a window similar to that shown in Fig-ure 1–11.

Figure 1–11 The default CircleArea project window.

Page 28: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

28 Chapter 1 • A Radically New Approach: C# and Windows

Move the mouse to button1 and click it. The application responds to this event andcalculates the area of the circle for which the radius was specified in the application. Yourscreen should now reflect the change and appear similar to Figure 1–12.

The answer shown in the label is the area of a circle with a radius of 12.3. All of thiswas accomplished by writing only two lines of code. Isn’t the remainder of this book goingto be fun?

Additional Program Details

The code in the CircleArea project is more complicated than the console application createdat the beginning of this chapter. In this section, we’ll examine the structure of the templatecode and leave the details of forms and controls for later chapters. In the following sectionswe’ll examine key portions of the template code in an attempt to understand the structure ofall C# Windows projects.

Figure 1–12 The area of a circle is calculated.

Page 29: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

Your First C# Windows Application 29

Namespaces

The projects’ namespace is named CircleArea. In the following listing, you also see addi-tional namespaces added by the AppWizard for this C# Windows project.

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

namespace CircleArea

The System namespace is a fundamental core namespace used by all C# projects. Itprovides the required classes, interfaces, structures, delegates, and enumerations required ofall C# applications.

The System.Drawing namespace provides access to a number of drawing tools. Forexample, the namespace classes include Brushes, Cursor, Fonts, Pens, and so on. Thenamespace structures include Color, Point, and Rectangle. Do you recall the Point structurefrom earlier in this chapter? The namespace enumerations include BrushStyle and PenStyle.

The System.Collections namespace contains the ArrayList, BitArray, Hashtable,Stack, StringCollection, and StringTable classes. The System.ComponentModel namespaceprovides support for the following classes; ArrayConverter, ByteConverter, DateTimeCon-verter, Int16Converter, Int32Converter, Int64Converter, and so on. Delegate support is alsoprovided for a variety of event handler delegates.

The System.Windows.Forms namespace provides class support for a variety of formsand controls. For example, classes are provided for Border, Button, CheckBox, CommonDi-alog, Forms, and ListBox. This class support spans dialog boxes, forms, and controls. Dele-gate support is provided for both forms and controls. Enumerations include enumerationsfor styles and states for forms and controls.

The System.Data namespace provides class support for handling data. Enumerationsallow various actions to be performed on data, including various sort options.

For a more detailed look at each of these namespaces, use the Visual Studio NET Helpoptions. Just be sure to set C# as the filter, as shown in Figure 1–13.

Page 30: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

30 Chapter 1 • A Radically New Approach: C# and Windows

You may want to stop at this point and examine other namespaces such as Win-dows.Forms and so on using the Help engine.

The Form

The next portion of code shows the basic class for the project, named Form1. Every applica-tion uses one form, so it should not be a surprise that the naming convention for the class isthe name of the base form, in this case Form1.

public class Form1 : System.Windows.Forms.Form

{ public double radius = 12.3; . . .

Figure 1–13 Additional namespace details are available with the Visual Studio NET Help engine.

Page 31: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

Your First C# Windows Application 31

/* * The main entry point for the application. * */ public static void Main(string[] args) { Application.Run(new Form1()); }}

The description for the Form1 class encompasses all of the remaining code in theproject. Here you will see variable declarations, control declarations, a variety of compo-nent initializations, control methods and, of course, Main().

Designer Variables

In this section, you will find listed the components that are used in the project.

/// <summary>/// Required designer variable./// </summary>private System.ComponentModel.Container components = null;private System.Windows.Forms.Button button1;private System.Windows.Forms.Label label1;

From our discussion of namespaces, note that the project’s container is brought intothe project via the System.ComponentModel namespace. In a similar manner, the Buttonand Label controls, named by default button1 and label1, are supported by the System.Win-dows.Forms namespace.

Initializing Components

The next portion of code initializes components for the project. Components include theform, controls placed on the form, form properties, and so on.

#region Windows Form Designer generated code/// <summary>/// Required method for Designer support - do not modify/// the contents of this method with the code editor./// </summary>private void InitializeComponent(){ this.components = new System.ComponentModel.Container(); this.Size = new System.Drawing.Size(296, 165); this.Text = "Form1"; this.label1 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button();

Page 32: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

32 Chapter 1 • A Radically New Approach: C# and Windows

label1.Location = new System.Drawing.Point(40, 48); label1.Text = "label1"; label1.Size = new System.Drawing.Size(224, 24); label1.TabIndex = 0; button1.Location = new System.Drawing.Point(104, 104); button1.Size = new System.Drawing.Size(88, 32); button1.TabIndex = 2; button1.Text = "button1"; button1.Click += new System.EventHandler (this.button1_Click); this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.Controls.Add (this.button1); this.Controls.Add (this.label1);}#endregion

The components and values returned to this portion of code are dependent on the size andplacement of the form and any controls placed in the form. All of this work was accom-plished using the designer form. Most of these values are initial properties for the form orcontrol they represent. For example:

button1.Location = new System.Drawing.Point(104, 104);button1.Size = new System.Drawing.Size(88, 32);

This portion of code initializes the Location and Size properties for the Button control,button1. You can view these initial property values as a static or initial form design. Many prop-erties are changed dynamically when the program executes. In this program, for example, thetext in the Label control’s Text property is changed when the mouse clicks the Button control.

The Event Handler

You might recall that during the design phase of the project, we double-clicked the mousetwice while over the Button control. By doing so, we automatically added a template for abutton1_Click event to the application, as follows:

private void button1_Click(object sender, System.EventArgs e){ label1.Text = (radius * radius * 22 / 7).ToString();}

This simply means that when the button is clicked, the code in this event handler isexecuted. The code in the event handler has nothing to do with the button event itself. Thecode in this example says that the Text property of the Label control, label1, will bechanged to the string to the right. The string to the right of the equal sign is actually anumeric calculation for the area of a circle with the number converted to a string with theuse of ToString().

Page 33: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing

Summary 33

The End

Finally, the Dispose() method is used to clean up unneeded items:

/// <summary>/// Clean up any resources being used./// </summary>protected override void Dispose( bool disposing ){ if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing );}

The use of the Dispose() method here frees system resources.

SummaryThis chapter has focused on the preliminary information necessary to use the Visual Studio.NET environment to build a simple console and Windows application. The chapter alsoprovided a quick overview of the C# language, pointing out those features that will be usedin the remainder of this book. Remember, if you are looking for a more detailed treatment ofC# language features, you’ll want to investigate our C# Essentials book, published by Pren-tice Hall (ISBN 0-13-093285-X), 2002.

The next two chapters will concentrate on describing C# forms, controls, and proper-ties. Once you have mastered these components, you’ll be ready to start developing robustC# Windows programs.

Page 34: A Radically New Approach: C# and Windows M · PDF fileWhen you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing