Hello World

A long-standing tradition among programmers is to begin study of any new language by writing a program that prints "Hello World" to the screen. In deference to tradition, the first windows applications you create will do just that.

In this section, you will create three progressively more interesting versions of the venerable Hello World program. These versions will demonstrate some of the fundamental features of a Windows application. The first version will be a console application that writes a line of text to the system console (also known as a Command Prompt Window. Some old-timers still call it a DOS box, which is technically no longer accurate.). The next version will be a true Windows application, even if it is somewhat limited. The final version will add a button to demonstrate event handling. (Chapter 4 will cover events in detail.)

2.2.1 Using a Text Editor

The tool you are most likely to use when developing Windows applications is Visual Studio .NET. You may use any editor you like, however. All source code and configuration files for all .NET applications (Windows and web) are flat ASCII text fileseasily created, read, and modified using any text editor, ranging from Notepad or WordPad (included with Windows) to powerful third-party code editors and development environments.

Both Visual Studio .NET and the C# command-line compilers support different language encodings. In Visual Studio .NET, encoding is accessed under File Advanced Save Options. The C# command-line compiler has a /codepage option to specify the codepage. The VB.NET command-line compiler does not support alternative encodings. In any case, the default code page is UTF8, which is a superset of flat ASCII.

Using Visual Studio .NET has several advantages. The code editor provides indentation and color coding of your source code, the IntelliSense feature helps you choose and enter the right commands and attributes, and the integrated debugger helps you find and fix errors in your code.

The disadvantage of using Visual Studio .NET, however, is that it automatically generates copious amounts of boilerplate code and default object names. As a beginner, you may be better off doing more of the work yourself, giving up the support of the IDE in exchange for the opportunity to see how things really work.

You enhance the clarity, readability, and maintainability of your program by using your own names for namespaces, classes, methods, and functions, rather than using the default names provided by Visual Studio .NET.

Each of the three versions of Hello World mentioned above will first be developed by using a simple text editor to create the source code. The same three versions will then be created using Visual Studio .NET.

All code examples will be presented in both VB.NET and C#, unless both language versions are nearly identical.

2.2.1.1 Hello World as a console application

The first version of the Hello World program created here will be a console application. A console application has no user interface (UI) other than a command prompt. It has no windows, buttons, menus, listboxes, or other graphical elements. All it can do is execute program code, accept input, and display text.

For most purposes, the input console is the keyboard and the output console is the command prompt window. The Console class of the .NET Framework encapsulates both the input and output console, and provides properties and methods for communicating with the console. Text written to (or read from) the console can also be directed to or from other devices or files using streams. The Hello World program shown here will just send some characters to the screen.

If a console application EXE file is double clicked in Windows Explorer, the console application will open its own command prompt window, execute, and close the window. For a quickly running program like Hello World, it all happens so fast that you barely see the screen flicker.

To execute a console application and actually see the results, open a command prompt and run the program by typing the executable name from the command line.

Using the Command Line in NET

For any of the tools or utilities provided as part of the .NET SDK to run from a command line, the Path property of the operating system environment for that command window must include the correct location of the tool or utility executable. The easiest way to ensure that the Path is set correctly is to not open a normal Command window (Start Programs Accessories Command Prompt), but instead to open a special command prompt window provided as part of .NET. This command window has the Path correctly set to include the locations of all the .NET tools and utilities.

Click on the Start button, and then Programs Microsoft Visual Studio .NET 2003 Visual Studio .NET Tools Visual Studio .NET 2003 Command Prompt. You will probably want to copy this shortcut to someplace more accessible, such as the Windows desktop or a quick launch toolbar.

To execute a console application, either navigate to the directory where the console application lives (using the cd command) and then type the name of the program, or enter the full path to the program as part of the name.

The code listings shown in Example 2-1 and Example 2-2 are the Hello World console applications in C# and VB.NET, respectively. These programs use the WriteLine method to output a line of text to the system console, which is your computer screen.

This book is not a primer on C#, VB.NET, or the .NET framework. We assume you are familiar with this material, and we will not explain the language fundamentals. For a full exploration of VB.NET, see Jesse Liberty's Programming Visual Basic .NET, and for C#, see his book Programming C# (both from O'Reilly).

A significant theme of this book is that the choice between C# and VB.NET is purely syntactic: you can express almost any programming idea in either language. Write in whichever language is more comfortable for you. The transition from VB.NET or VBScript to VB.NET may be slightly easier than to C#, but much of the Microsoft and third-party documentation is in C#.

This book shows most examples in both languages, with a slight preference for C# because it is a bit more terse. In any case, you will notice that in most cases, the differences between the languages are small and easily understood.

Open a text editor, such as Notepad, and enter the code shown in Example 2-1 or Example 2-2. Save the file to the name shown in the caption for each code listing.

Example 2-1. Hello World console application in C# (HelloWorld-console.cs)

figs/csharpicon.gif

namespace ProgrammingWinForms
{
 public class HelloWorld
 {
 static void Main( ) 
 {
 System.Console.WriteLine("Hello World");
 }
 }
}

Example 2-2. Hello World console application in VB.NET (HelloWorld-console.vb)

figs/vbicon.gif

namespace ProgrammingWinForms
 public class HelloWorld
 shared sub Main( ) 
 System.Console.WriteLine("Hello World")
 end sub
 end class
end namespace

The principal differences between C# and VB.NET are that C# is case sensitive, statements in C# are terminated with a semicolon, and namespaces, classes, and methods in C# are contained within curly braces, whereas VB.NET uses the keyword end.

Although VB.NET is not case sensitive, Visual Studio .NET does impose its own casing rules on VB.NET source code (something that is lacking in C#). Since many of the examples in this book were created outside Visual Studio .NET, the VB.NET code in those examples does not necessarily follow the standard casing. It still compiles fine.

2.2.1.2 Compiling the program

To convert your source code to an executable program, it must be compiled. When working outside Visual Studio .NET, this is done using a command-line compiler. The SDK provides compilers for each supported language. This book uses both the C# and the VB.NET compilers.

Open the Visual Studio .NET command prompt, as discussed in the . earlier sidebar This will ensure that the proper path is set. Navigate to the directory where the source file is saved, using the cd command.

To compile the C# version of the Hello World program (the code shown in Example 2-1), use the following command (assuming you have saved the source file with the name HelloWorld-console.cs, as shown in the caption of Example 2-1):

figs/csharpicon.gif

csc HelloWorld-console.cs

To compile the VB.NET version, use the following command (again assuming the source file was saved with the name HelloWorld-console.vb as shown in the caption in Example 2-2):

figs/vbicon.gif

vbc HelloWorld-console.vb

In either case, the source file will be processed by the compiler and an EXE file will be created in the current directory. The name of the EXE file will be the same as the source code, without the extension (HelloWorld-console) followed by the extension .exe. Thus, HelloWorld-console.exe.

You can execute the program by typing its name on the command line. Figure 2-1 shows the results of opening a Visual Studio .NET command prompt window, navigating to the proper directory, compiling, and running Hello World for the console in C#.

Figure 2-1. Compiling and running HelloWorld-console in C#

figs/pnwa_0201.gif

This was the simplest kind of compilation. Often, however, you will want the output name to be different from the input name, and for all but the simplest programs, there may be other files that must be referenced as part of the compilation. You control these aspects of command-line compiling with command-line switches. A command-line switch begins with a forward slash. To see all the available options available to the compiler, look in the SDK documentation or enter the appropriate commands:

figs/csharpicon.gif

csc /?

figs/vbicon.gif

vbc /?

Compile the programs again, this time explicitly specifying the name of the output file and the type of executable (console application). To do so, use the appropriate command line:

figs/csharpicon.gif

csc /out:csHelloWorld-console.exe /target:exe HelloWorld-console.cs

figs/vbicon.gif

vbc /out:vbHelloWorld-console.exe /target:exe HelloWorld-console.vb

The /out parameter specifies the output filename. If no /out parameter is specified, the output file will take its name from the source file that contains the Main procedure (in the case of EXE outputs) or the first source file specified (for non-EXE outputs). If there is no path information as part of the /out parameter, then the output file will be created in the current directory. You can qualify the filename with a path, either absolute or relative, to specify the output file location.

The /target parameter specifies the type of executable that will be created. You may also use /t as a shortcut form of /target. Table 2-1 lists four legal values for the /target parameter.

Table 2-1. Legal values of the /target parameter

Value

Short form

Description

/target:exe

/t:exe

Generates a console application with an extension of .exe. This is the default if no target option is specified. A Main procedure is required in at least one source file.

/target:library

/t:library

Generates a dynamic-link library (DLL). No Main procedure is required in any source file. If no /out parameter is specified, the output file will have an extension of .dll.

/target:module

/t:module

Generates a module that can be added to an assembly. If no out parameter is specified, the output file will have an extension of .netmodule. This option is available only via the command line; it is not available from within Visual Studio .NET.

/target:winexe

/t:winexe

Generates an executable Windows program, with an extension of .exe. A Main procedure is required in at least one source file.

One of the most commonly used compiler options (in VB.NET compilations, especially) is /reference (the short form is /r). This parameter specifies a file that contains an assembly manifest. The manifest exposes the assembly metadata. This allows other parts of the project to learn about and use any types (classes, member variables, methods, etc.) contained in the referenced file(s). If these types have public accessibility, then they will be available to the project being compiled.

Typically, the referenced files are DLLs that contain the .NET Framework class libraries, although you may also reference class libraries developed by yourself or others.

C# does not need the references in the command-line compile because a file called csc.rsp contains "default" references for the C# compiler. There is no equivalent in VB.NET, so the references must be included in the command line.

You can reference multiple files either by using multiple /reference parameters or by using a single parameter with a comma-separated list of filenames. Be certain not to include any spaces between the filenames if referencing multiple files with a single /r. The following two commands are equivalent:

figs/vbicon.gif

vbc /out:binvbStockTickerCodeBehind.dll /t:library /r:system.dll,
system.web.dll,system.web.services.dll,
system.data.dll,system.xml.dll StockTickerCodebehind.vb
 
vbc /out:binvbStockTickerCodeBehind.dll /t:library 
/r:system.dll /r:system.web.dll /r:system.web.services.dll
/r:system.data.dll /r:system.xml.dll StockTickerCodebehind.vb

In these command-line compilations, the VB.NET compiler is executed to compile a source code file named StockTickerCodebehind.vb. The output file, vbStockTickerCodeBehind.dll, is a library file located in the bin subdirectory under the current directory. Five other DLL's are referenced: system.dll, system.web.dll, system.web.services.dll, system.data.dll, and system.xml.dll.

Sometimes you need to reference an assembly that is not located in either the CLR's system directory or the current directory of the command prompt window. In this case, use the /lib (with C#) or /libpath (with VB.NET) option to specify a directory to search in. You can search multiple directories by passing in a comma-separated list of directories. The compiler will first search the current directory of the command window, then the CLR system directory, and finally the directories specified in the /lib or /libpath options.

The /bugreport option aids in debugging compile problems. This option opens a text file and causes the compiler to put into it a copy of all the source files used in the compilation (you will probably want to condense and isolate the problem area), all the version information and compiler options, and the compiler output, if any. It will also prompt you for a description of the problem and how you think it should be fixed. These descriptions will accept carriage returns, so you can write a multiline description. The /bugreport option takes a fully qualified filename as its value.

The @ option allows you to specify a file, called a response file, which contains compiler options and source code files, just as if they had been entered manually from the command line. Use multiple @ options to specify multiple response files. Response files can have multiple lines, but each compiler option must be on a single line with no line break. The # symbol can be used in response files to comment lines.

When compiling EXE files, the source code must have at least one Main( ) method as an entry point for the program. This entry point must be static in C# or Shared in VB.NET. It can return either void (a sub in VB.NET) or an integer. If there are multiple Main( ) methods in the application, use the /main option to specify the class that contains the Main( ) method you will use as the entry point.

You can tell the compiler to search for source code files either in the current directory or in a specified directory. To do so, include an optional path name (absolute or relative) or a wildcard as part of the input file. For example, the following command line compiles a Windows application called HelloWorld.exe, using all the C# files in the current directory beginning with the characters HelloWorld:

figs/csharpicon.gif

csc /out:HelloWorld.exe /t:winexe HelloWorld*.cs

The following command line will search for all similarly named source files in the c:projects directory:

figs/csharpicon.gif

csc /out:HelloWorld.exe /t:winexe c:projectsHelloWorld*.cs

You can also search for source files in the current or specified directory, plus all of their subdirectories, using the /recurse option. For example, the following command line will use all C# source code files in the current directory and all its subdirectories:

figs/csharpicon.gif

csc /out:HelloWorld.exe /t:winexe /recurse:*.cs

This command line will search for all the C# source code files in the deploy subdirectory under the current directory, plus all subdirectories under deploy:

figs/csharpicon.gif

csc /out:HelloWorld.exe /t:winexe /recurse:deploy*.cs

2.2.1.3 Hello World as a Windows application

The next version of Hello World you create will be a very simple Windows application. Example 2-3 shows the code for this program in C# and Example 2-4 shows it in VB.NET. In both versions, a Windows Form is created with the text on the titlebar set to Hello World.

Example 2-3. Hello World Windows application in C# (HelloWorld-win.cs)

figs/csharpicon.gif

using System.Windows.Forms;
 
namespace ProgrammingWinForms
{
 public class HelloWorld : System.Windows.Forms.Form
 {
 public HelloWorld( )
 {
 Text = "Hello World";
 }
 
 static void Main( ) 
 {
 Application.Run(new HelloWorld( ));
 }
 }
}

Example 2-4. Hello World Windows application in VB.NET (HelloWorld-win.vb)

figs/vbicon.gif

imports System.Windows.Forms
 
namespace ProgrammingWinForms
 public class HelloWorld : inherits System.Windows.Forms.Form
 public sub New( )
 Text = "Hello World"
 end sub
 
 shared sub Main( ) 
 Application.Run(new HelloWorld( ))
 end sub
 end class
end namespace

The first line of Example 2-3 and Example 2-4 imports the System.Windows.Forms namespace:

figs/csharpicon.gif

using System.Windows.Forms;

figs/vbicon.gif

imports System.Windows.Forms

This example lets you refer to objects in this namespace without the full qualification. When you declare the form, you are then free to refer to the base class as either System.Windows.Forms.Form or simply as Form.

The third line declares the Form class HelloWorld:

figs/csharpicon.gif

public class HelloWorld : System.Windows.Forms.Form

figs/vbicon.gif

public class HelloWorld : inherits System.Windows.Forms.Form

The VB.NET version can be written equivalently as:

figs/vbicon.gif

public class HelloWorld
inherits System.Windows.Forms.Form

Notice that the latter version is on two lines, and that it has neither a colon nor the VB.NET line-continuation character.

However you mark the derivation, the fact that your new class derives from Windows.Forms.Form makes it a Windows Form application.

The next several lines contain the constructor for the HelloWorld class. In this example, you will set the window caption from within the form's constructor by assigning a string to the form's Text property:

figs/csharpicon.gif

public HelloWorld( )
{
 Text = "Hello World";
}

figs/vbicon.gif

public sub New( )
 Text = "Hello World"
end sub

Once again, the Main( ) method is the entry point to the program:

figs/csharpicon.gif

static void Main( )
{
 Application.Run(new HelloWorld( ));
}

figs/vbicon.gif

shared sub Main( )
 Application.Run(new HelloWorld( ))
end sub

The Application class is contained within the System.Windows.Forms namespace. Launch a Windows application by calling the static Run method of the Application class.

As always, the source code must be compiled to create an executable program. The command line for compiling the program is:

figs/csharpicon.gif

csc /out:csHelloWorld-win.exe /t:winexe HelloWorld-win.cs

figs/vbicon.gif

vbc /out:vbHelloWorld-win.exe /t:winexe /r:system.dll,
system.windows.forms.dll HelloWorld-win.vb

In the C# compilation, the output file is called csHelloWorld-win.exe, and in the VB.NET compilation it is vbHelloWorld-win.exe. Both files are located in the current directory. In both cases, the target output type is a Windows application. The VB.NET command line also includes references to several .NET class libraries.

When either output EXE file is executed, the results will look like that shown in Figure 2-2. Notice that the title of the form was set to Hello World. The form has all the functionality one would expect of a rudimentary Windows application: the window can be moved or resized using standard Windows techniques; clicking on the icon in the upper-left corner of the window drops down the standard window menu; and the minimize, maximize, and close window buttons are present and functional in the upper-righthand corner. Not bad for a very small amount of code.

Figure 2-2. Hello World as a Windows application

figs/pnwa_0202.gif

Notice the correlation, if only by convention, between the namespace referenced in the source code and the files referenced in the compile command. Namespaces are referenced in the source code with using statements in C# and Imports statements in VB.NET. These namespaces are themselves contained within assembly files, most typically DLLs. Table 2-2 shows the correspondence between some of the commonly used namespaces and the assemblies in which they are contained.

Table 2-2. Correspondence of source code and compiler references

Source-code reference

Compiler reference

Comment

-

system.dll

Supplies fundamental classes and base classes. Not necessary in the source code because it is referenced by default.

System.Windows.Forms

system.windows.forms.dll

Contains classes necessary to instantiate form objects.

System.Collections

-

Provides classes and interfaces used by various collections, including Arrays and ArrayLists. Not necessary in the compiler reference because it is included in mscorlib.dll, which is referenced by default.

System.Drawing

system.drawing.dll

Supplies basic drawing capabilities, including Font and Pen classes, and Color, Point, and Rectangle structures.

2.2.1.4 Hello World Windows application with a button

The final step in the evolution of this Hello World application will be the addition of a control that generates an event in response to a user action. For this example, you will add a button control that raises the click event when a user clicks on the button. An event handler will handle this click event. Chapter 4 discusses events in detail.

The code in Example 2-5 adds a button control and the click-event handler to the previous example in C#. The additional lines of code are shown in boldface. Example 2-6 shows the equivalent example in VB.NET.

Example 2-5. Hello World Windows application with button control in C# (HelloWorld-win-button.cs)

figs/csharpicon.gif

using System;
using System.Drawing;
using System.Windows.Forms;
 
namespace ProgrammingWinForms
{
 public class HelloWorld : System.Windows.Forms.Form
 {
 private Button btn;

 public HelloWorld( )
 {
 Text = "Hello World";
 btn = new Button( );
 btn.Location = new Point(50,50);
 btn.Text = "Goodbye";
 btn.Click += new System.EventHandler(btn_Click);

 Controls.Add(btn);
 }
 
 static void Main( ) 
 {
 Application.Run(new HelloWorld( ));
 }
 
 private void btn_Click(object sender, EventArgs e)
 {
 Application.Exit( );
 }

 }
}

Example 2-6. Hello World Windows application with button control in VB.NET (HelloWorld-win-button.vb)

figs/vbicon.gif

imports System
imports System.Drawing
imports System.Windows.Forms
 
namespace ProgrammingWinForms
 public class HelloWorld : inherits System.Windows.Forms.Form
 
 Private WithEvents btn as Button

 public sub New( )
 Text = "Hello World"
 btn = new Button( )
 btn.Location = new Point(50,50)
 btn.Text = "Goodbye"

 Controls.Add(btn)
 end sub
 
 public shared sub Main( ) 
 Application.Run(new HelloWorld( ))
 end sub
 
 private sub btn_Click(ByVal sender as object, _
 ByVal e as EventArgs) _
 Handles btn.Click
 Application.Exit( )
 end sub

 end class
end namespace

The C# code from Example 2-5 is compiled with the following command line:

figs/csharpicon.gif

csc /out:HelloWorld-Win-Button.exe /t:winexe HelloWorld-Win-Button.cs

The VB.NET code from Example 2-6 is compiled with this command line:

figs/vbicon.gif

vbc /out:vbHelloWorld-win-Button.exe /t:winexe /r:system.dll,
system.windows.forms.dll,system.drawing.dll HelloWorld-win-Button.vb

As above, the VB.NET compiler does not reference any assemblies by default, so they must be explicitly included in the command line.

When the code from Example 2-5 or Example 2-6 is compiled and run, the results look like Figure 2-3.

Figure 2-3. Hello World with a button control

figs/pnwa_0203.gif

In the code that created this application, a private member variable was declared to represent the button:

figs/csharpicon.gif

private Button btn;

figs/vbicon.gif

Private WithEvents btn as Button

The WithEvents keyword in the VB.NET code is required for event handling and will be explained in Chapter 4.

Inside the HelloWorld( ) constructor, the button variable btn is instantiated as a new instance of the Button class and the Location property is specified as a Point:

figs/csharpicon.gif

btn = new Button( );
btn.Location = new Point(50,50);

figs/vbicon.gif

btn = new Button( )
btn.Location = new Point(50,50)

In the C# version, the event handler for the Click event is added.

figs/csharpicon.gif

btn.Click += new System.EventHandler(btn_Click);

In the VB.NET version, the event handler is hooked up by the combination of the WithEvents keyword in the btn declaration and the Handles keyword in the event-handler method declaration, as you will see momentarily.

Finally in the constructor, the button is added to the Controls collection on the form:

figs/csharpicon.gif

Controls.Add(btn);

figs/vbicon.gif

Controls.Add(btn)

The btn_Click method responds to the button Click event:

figs/csharpicon.gif

private void btn_Click(object sender, EventArgs e)
{
 Application.Exit( );
}

figs/vbicon.gif

private sub btn_Click(ByVal sender as object, _
 ByVal e as EventArgs) _
 Handles btn.Click
 Application.Exit( )
end sub

Unlike in VB6, the name of the event handler is insignificant. The Handles keyword determines the events handled by each event-handler method.

Chapter 4 will describe the event handler methods in detail. For now, suffice it to say that when the button is clicked, the Exit( ) method of the Application class is called, which closes the application.

2.2.2 Using Visual Studio .NET

Now that you have created the three Hello World programs using a text editor, you will make the same three programs using Visual Studio .NET. This chapter offers a whirlwind tour of the IDE to show how easy it is to create applications. The next chapter covers Visual Studio .NET in greater detail.

2.2.2.1 Hello World as a console application

Open Visual Studio .NET. You will see a Start page with a list of your previous projects, if any, an Open Project button, and a New Project button. Click on the New Project button.

You will be presented with the New Project dialog box. You will see a list of Project Types in the left pane and a list of Templates in the right pane.

In the left pane, click on either Visual Basic Projects or Visual C# projects, depending on which language you wish to use.

In the right pane, click on Console Application.

The name will default to ConsoleApplication1 and the Location will be the default project directory for your system.

You can change the default Location by clicking Tools Options. In the tree control on the left, click on Environment Projects and Solutions. You will see an edit field on the right labeled Visual Studio projects location, along with a Browse button. Either type or browse to the new default directory.

Change the name of the project to csHelloWorld-Console or vbHelloWorld-Console, depending on which language you are using. The dialog box will look like Figure 2-4.

Figure 2-4. New Project dialog box

figs/pnwa_0204.gif

As indicated by the label below the Location edit field, Visual Studio .NET will create a project in a subdirectory with the same name as the project, located under the default location.

Click OK to create the new project.

Visual Studio .NET will cook for a few moments, and then present a code-editing screen, along with menus and toolbars along the top and information windows along the right edge. If you are using C#, it will look something like Figure 2-5.

Figure 2-5. C# Console application code-editing screen in Visual Studio .NET

figs/pnwa_0205.gif

If you are using VB.NET, it will look like Figure 2-6.

Figure 2-6. VB.NET Console application code-editing screen in Visual Studio .NET

figs/pnwa_0206.gif

The next chapter will cover Visual Studio .NET in detail. For now, focus on the code windows.

If you are using C#, notice the commented lines inside the Main( ) method. Place your mouse cursor at the end of the last commented line and press Enter. This will put the cursor on the next line, properly indented and ready to enter code.

If you are using VB.NET, put your cursor inside the Main( ) method and tab to get the proper indentation.

Type in the appropriate line of code:

figs/csharpicon.gif

Console.WriteLine("Hello World");

figs/vbicon.gif

Console.WriteLine("Hello World")

As soon as you type the period after the word Console, IntelliSense will display a list of all the possible methods and properties available to the Console class. (Remember that C# is case sensitive.)

You can use the arrow key or the mouse to select one of the methods or properties. Alternatively, just start typing. As you do, the first available selection starting with that character will be highlighted. Successive characters will refine the selection. When the desired method or property is highlighted, press Tab or any other key on the keyboard.

If you press Tab, the selection will be entered in the line of code. If you press any other key, the selection will be entered in the line of code, and that key character will also be entered. When you get to the point of entering arguments for the method, a tool tip will pop up showing all the different valid signatures. The next chapter will explore the IntelliSense feature in more detail.

The behavior of C# and VB.NET differ here. In C#, pressing Enter will insert the selected item without adding a new line, while in VB.NET, Enter will add a new line. Tab works the same in either language, inserting the selection with no additional characters or new lines.

Normally you would press F5 to start a program. However, if you do this for a console application, it will go by too fast to see.

Press Ctrl-F5 to run the program without debugging. A console window, similar to a command prompt window, will appear with the output of your program. It will look something like Figure 2-7.

Figure 2-7. Console application output

figs/pnwa_0207.gif

As you may recall, when you created the console application using a text editor, the relevant line of code had the class System prepended to it, as in:

System.Console.WriteLine("Hello World");

That is not necessary here because Visual Studio .NET automatically included a reference to the System namespace. In C#, this is immediately apparent from the first line in the code editor:

figs/csharpicon.gif

using System;

In VB.NET, it is less obvious, but several namespaces are imported by default, rather than with explicit Imports statements. You can see them by right-clicking on the solution in Solution Explorer and selecting Properties, to display the Property Pages for the project (not to be confused with the Properties window). Under Common Properties, click on Imports to see the namespaces imported by default.

Unlike C#, Visual Studio .NET:

  • Automatically provides the boilerplate code to create the skeleton of a program
  • Automatically provides default namespace references
  • Automatically provides default assembly references
  • Provides IntelliSense to minimize typing and coding errors
  • Automatically compiles the program when you run the application

2.2.2.2 Hello World as a Windows application

As you did with the text-editor versions of Hello World, now create a new version of the Hello World program as a Windows applicationthis time using Visual Studio .NET.

Open Visual Studio .NET and click on the New Project button on the Start page. In the left side of the New Project dialog box, select either Visual Basic Projects or Visual C# Projects, depending on the language you want to use.

In the right side of the dialog box, select Windows Application. The default name of the project will be WindowsApplication1. Change this name to either csHelloWorld-Win or vbHelloWorld-Win, depending on which language you are using. The New Project dialog should look like Figure 2-8.

Figure 2-8. New Project Dialog for Hello World Windows application

figs/pnwa_0208.gif

The project will be created in a subdirectory with the same name as the project, located under the default location, as indicated by the label under the Location edit field.

After clicking OK on the dialog box, you will be presented with the Visual Studio .NET design page, similar to Figure 2-9.

Figure 2-9. Design page for Hello World Windows application

figs/pnwa_0209.gif

Figure 2-9 is similar to the console application screen shown in Figure 2-5, except the main design view contains a visual representation of a Windows Form, rather than a code-editing window, and the Properties window along the lower-right side of the screen now shows properties for the Form1.cs file, which is currently highlighted in the Solution Explorer.

Click on the form on the design surface. The Properties window will display the properties of the current control, which in this case is the form. Slide down the Properties window until you see the Text property. It currently has the value Form1. Change the value to Hello World. You will see the titlebar of the form change to say Hello World.

To differentiate it even more from the console version, add a label to the form. Click on the View menu item, then ToolBox. The Toolbox will appear on the screen. Click on the Label control and drag it onto the form. Grab the label control (by clicking on it and dragging) and move it to a suitable location. While the label control is selected, look at the Properties window. It will show the properties for the label. Change the Text property to Visual Studio .NET Version. If necessary, resize the label by clicking on one of the resizing handles and dragging it to enlarge the label until the text no longer wraps. Visual Studio .NET should look something like Figure 2-10.

Figure 2-10. Hello World Windows application with label

figs/pnwa_0210.gif

Run the program by pressing F5 or clicking on the Start icon (figs/icon_start.gif) on the toolbar. When you do, the window shown in Figure 2-11 will open.

Figure 2-11. Hello World Windows application

figs/pnwa_0211.gif

As with the manually coded version, this is a full-fledged Windows application, which can be moved and resized, opens a fully functional window menu once you click the icon in the upper-left corner, and minimize, maximize and close window buttons in the upper-right corner.

2.2.2.3 Hello World Windows application with a button

The final step in the evolution of this Hello World program is the addition of a button that can respond to a user action. As with the hand-coded version, the button will raise a click event that the program will handle. However, as you will see, Visual Studio .NET will write most of the code for you.

Open the Toolbox once again. You can open it by either hovering the mouse cursor over Toolbox tab on the left edge of the design surface or clicking on View Toolbox from the menu.

By default, the Toolbox will auto-hide, disappearing from view when the cursor is not over it. It will pop out when the cursor is placed on the Toolbox tab. You can turn this feature off by clicking on the pushpin icon at the top of the Toolbox. The pushpin will be vertical when Auto-Hide is off and sideways when it is on.

Click on the Button control and drag it to a suitable location on the form, or double-click it in the Toolbox to add it to the form and then drag it into position.

While the button is highlighted, go to the Properties window and change the text property to Goodbye. The text written on the button will change accordingly.

Now create and hook up the default event handler by double-clicking the button.

A code window will open up with an event handler method skeleton already created. The cursor will be inside the method, ready to type. Enter the appropriate line of code:

figs/csharpicon.gif

Application.Exit( );

figs/vbicon.gif

Application.Exit( )

As you saw when entering the code for the Windows version of the console application above, IntelliSense will pop up all the available methods and properties of the Application class as soon as you type the period.

The screen should look like Figure 2-12 if you are using C# or Figure 2-13 if you are using VB.NET.

Figure 2-12. Hello World button event handler in C#

figs/pnwa_0212.gif

Figure 2-13. Hello World button event handler in VB.NET

figs/pnwa_0213.gif

Run the program by pressing F5 or clicking on the Start icon (figs/icon_start.gif) on the toolbar. When you do, the window shown in Figure 2-14 will open.

Figure 2-14. Hello World Windows application with button

figs/pnwa_0214.gif

Clicking on the Goodbye button will raise the click event, which will be handled by the Button1_Click event handler method. Visual Studio .NET automatically provides all the code necessary for creating that event handler and hooking it to the event, greatly easing your programming chores.

Windows Forms and the .NET Framework

Getting Started

Visual Studio .NET

Events

Windows Forms

Dialog Boxes

Controls: The Base Class

Mouse Interaction

Text and Fonts

Drawing and GDI+

Labels and Buttons

Text Controls

Other Basic Controls

TreeView and ListView

List Controls

Date and Time Controls

Custom Controls

Menus and Bars

ADO.NET

Updating ADO.NET

Exceptions and Debugging

Configuration and Deployment



Programming. NET Windows Applications
Programming .Net Windows Applications
ISBN: 0596003218
EAN: 2147483647
Year: 2003
Pages: 148

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net