• No results found

WinForms & Windows Applications

In document c# (Page 190-200)

Lesson Plan

Today we will start building Windows Applications in C#. We will start by looking at the architecture of Windows Application and their support in .Net. Later, we will design our first "Hello WinForm" Application and learn about various windows form controls. Finally, we will look at how Visual Studio.Net eases the creation of Windows Applications.

Windows Applications and .Net

C# and .Net provide extensive support for building Windows Applications. The most important point about windows applications is that they are 'event driven'. All windows applications present a graphical interface to their users and respond to user interaction. This graphical user interface is called a 'Windows Form', or 'WinForm' for short. A windows form may contain text labels, push buttons, text boxes, list boxes, images, menus and vast range of other controls. In fact, a WinForm is also a windows control just like a text box, label, etc. In .Net, all windows controls are represented by base class objects contained in the System.Windows.Forms namespace.

WinForm Basics

As stated earlier, .Net provides the WinForm and other controls through base classes in the

System.Windows.Forms namespace. The class System.Windows.Forms.Form is the base class of all WinForms in .Net. In order to design a windows application, we need to:

1.Create a Windows Application project in Visual Studio.Net, or add references to System.Windows.Forms and System.Drawing to your current project. If you are not using Visual Studio at all, use the /reference option of the command line compiler to add these assemblies.

2.Write a new class to represent the WinForm and derive it from the System.Windows.Forms.Form class:

class MyForm : System.Windows.Form {

...

}

3.Instantiate various controls, set their appropriate properties and add these to MyForm's Controls collection.

4.Write another class containing the Main() method. In the Main() method, call the System.Application.Run() method, supplying it with an instance of MyForm.

191

class Test {

static void Main() {

Application.Run(new MyForm());

} }

The Application.Run() method registers your form as a windows application in the operating system so that it may receive event messages from the Windows Operating System.

Building the "Hello WinForm" Application

Let's build our first windows application, which we will call "Hello WinForm". The application will present a simple window with a "Hello WinForm" greeting at the center. The source code of the program is:

using System;

using System.Windows.Forms;

using System.Drawing;

namespace CSharpSchool {

class Test {

static void Main() {

Application.Run(new MyWindow());

} }

class MyWindow : Form {

public MyWindow() : base() {

this.Text = "My First Windows Application";

this.Size = new Size(300, 300);

Label lblGreeting = new Label();

lblGreeting.Text = "Hello WinForm";

lblGreeting.Location = new Point(100, 100);

this.Controls.Add(lblGreeting);

192

} } }

Understanding the Code

At the start, we included three namespaces in our application:

using System;

using System.Windows.Forms;

using System.Drawing;

The System namespace, as we stated in the first lesson, is the necessary ingredient of all C# applications. In fact, the Application class that we used later in the Main() method is defined in this namespace. The

System.Windows.Forms namespaces contains the base classes for windows controls, e.g. Form, Label and Button.

Finally, including the System.Drawing namespace is necessary as it contains the classes related to the drawing of controls. The Size and Point classes used later in the program are actually defined in the System.Drawing

namespace.

Later, we derived a new class, 'MyWindow', from the Form class defined in System.Windows.Forms.

class MyWindow : Form {

...

}

In the constructor of MyWindow, we specified the size and title of the form (by setting the size and text properties).

The size is defined using the System.Drawing namespace's Size class. We passed two integers to the constructor of Size to specify the width and the height of the form.

public MyWindow() : base() {

this.Text = "My First Windows Application";

this.Size = new Size(300, 300);

Next in the constructor, we created a text label and added it to the Controls collection of the Form. A text label is used to write some text on the form. The System.Windows.Forms.Label class defines a text label in a Windows application. We set the text of the Label using its Text property, which is of the string type. All the controls contained by a form must be added to its Controls collection; hence we have also added our label to this collection.

public MyWindow() : base() {

193

this.Text = "My First Windows Application";

this.Size = new Size(300, 300);

Label lblGreeting = new Label();

lblGreeting.Text = "Hello WinForm";

lblGreeting.Location = new Point(100, 100);

this.Controls.Add(lblGreeting);

}

Finally, we have created a Test class containing the Main() method. In the Main() method, we have instantiated the MyWindow class and passed its reference to the Application.Run() method so it may receive messages from the Windows Operating System.

When we execute the above code, the following screen is displayed:

To close the application, press the close button on the title bar.

Adding Event Handling

Let's now add a button labeled 'Exit' to the form. The 'Exit' button will close the application when it is clicked. In .Net, Push Buttons are instances of the System.Windows.Forms.Button class. To associate some action with the button click, we need to create an event handler and register (or add) it to the Button's Click event. Below is the code for this application.

194

using System;

using System.Windows.Forms;

using System.Drawing;

namespace CSharpSchool {

class Test {

static void Main() {

Application.Run(new MyWindow());

} }

class MyWindow : Form {

public MyWindow() : base() {

// Form

this.Text = "My First Windows Application";

this.Size = new Size(300, 300);

this.StartPosition = FormStartPosition.CenterScreen;

// Label

Label lblGreeting = new Label();

lblGreeting.Text = "Hello WinForm";

lblGreeting.Location = new Point(100, 100);

// Button

Button btnExit = new Button();

btnExit.Text = "Exit";

btnExit.Location = new Point(180, 180);

btnExit.Size = new Size(80, 30);

btnExit.Click += new EventHandler(BtnExitOnClick);

// Adding controls to Form

this.Controls.AddRange(new Control[] {lblGreeting, btnExit});

}

public void BtnExitOnClick(object sender, EventArgs e) {

Application.Exit();

195

} } }

In the constructor of MyWindow, first we have set certain properties of the Form. In this code, we have also used the StartPosition property of the Form, which sets the position of the form on the screen when the application starts. The type of this property is an enumeration called 'FormStartPosition'. We have set the start position of the form to the center of the screen.

The new inclusion in the code is the Exit button called 'btnExit'. We have created the button using the base class System.Windows.Forms.Button. Later, we have set various properties of the button, specifically its text label (Text), its Location and its Size. Finally, we have created an event handler method for this button called

BtnExitOnClick(). In the BtnExitOnClick() method, we have written the code to exit the application. We have also subscribed this event handler to the btnExit's Click event (To understand the event handling in C#, see lesson 10 of the C# school). In the end, we have added both the label and the button to the form's Controls collection. Note that this time we have used the AddRange() method of form class to add an array of controls to the Controls collection of form. This method takes an array of type Control as its parameter.

When the code is run, the following window will be displayed:

Now you can press either the Exit Button or the close button at title bar to exit the application.

196

Visual Studio.Net & its IDE (Integrated Development Environment)

Most of the time, you will be using Visual Studio.Net to develop Windows applications in C#. Visual Studio.Net provides a lot of tools to help develop applications and cuts out a lot of work for the programmer. Visual

Sutdio.Net provides a standard code editor and IDE for all .Net applications, along with a standard debugger, project and solution settings, form designer, integrated compiler and lot of other useful tools.

IntelliSense and Hot Compiler

The Visual Studio.Net IDE provides a standard text editor to write .Net applications. The text editor is loaded with IntelliSense and a hot compiler. IntelliSense gives the text editor the ability to suggest different options in the programming context. For example, when you place a dot after the name of an object, the IDE automatically provides you a list of all the members (properties, methods, etc) of the object. The following figure shows IntelliSense at work in the Visual Studio.Net IDE.

The hot compiler highlights the syntax errors in your program as you type the code. The following figure shows an illustration of the hot compiler at work in Visual Studio.Net.

197

Code Folding

One of the pleasant new features introduced in Visual Studio.Net is code folding. With code folding, you can fold/unfold the code using the + and - symbols. Usually the code can be folded/unfolded at each scope boundary (method, class, namespace, property, etc). You can also define regions within your code and can fold/unfold the code within the region. The region is defined using the #region...#endregion preprocessor directives.

Integrated Compiler, Solution builder and Debugger

Visual Studio.Net provides an integrated compiler to compile and execute your application during development.

You can either compile a single source file or the complete project and solution (a group of files that make up an application). Once you have compiled your application, you can debug it using the Visual Studio.Net debugger.

You can even create an installer for your application using Visual Studio.Net!

Form Designer

Perhaps the most useful feature of the Visual Studio.Net IDE is its form designer. The form designer allows you to design the graphical user interface just by placing the controls on the form from the Toolbox. You can set a lot of properties of the form and its controls using the Properties window.

The Visual Studio.Net IDE automatically writes the code in the source file as you place the controls on the form and change their properties. You can also use the IDE to create and set up the event handlers for your controls. The following figure presents an introductory view of the Visual Studio.Net Form Designer and its different supporting windows.

198

You can see the toolbox window at the left hand side (#1) and the properties window at the right hand side (#2) of the above snapshot. The toolbox allows you to add different controls to your form. Once the control is placed on the form, you can change its various properties from the Properties window. You can also change the location and size of the controls using the mouse. Event properties can be changed by switching to the Event Poperties pane (#3) in the Properties Window.

The Toolbox, Properties Window, Help Window, Solution Explorer Window, Class View Window, Output Window and other helping windows in Visual Studio IDE can be set for Docking and Auto hiding. Windows that are set for auto hide appears only when they get focus (e.g. they have mouse pointer over them or receive a mouse click), and hide when they lose focus. A window can be set for auto hide by the button marked #4 in the above figure. The hidden windows are always accessible through the left and right hand panes of the form designer window. The right hand pane is marked with #5 in the above figure and has got the class view, help and solution explorer windows in the hidden state. If some of these windows are not visible in your visual studio IDE, you can make them visible from the View menu on the standard menu bar.

Solution Explorer

The Solution Explorer is a very useful window. It presents the files that make up the solution in a tree structure. A solution is a collection of all the projects and other resources that make up a .Net application. A solution may contain projects created in different .Net based languages like VB.Net, VC#.Net and VC++.Net. The following figure presents a snapshot of the Visual Studio.Net Solution Explorer.

199

The Reference node contains all the assemblies referenced in the respective project. 'App.ico' is the icon file for the application. AssemblyInfo.cs is a C# file that contains information about the current assembly. Form1.cs in the above figure is the name of the source file of the program.

A .Net solution is saved in a .sln file, a C# project is saved in a .csproj file and C# source code is saved in a .cs file.

It is important to understand here that Projects and Solutions are standards of Visual Studio.Net and are not the requirement of any .Net language. In fact, the language compiler is not even aware of any project or solution.

Menus in the Visual Studio .Net IDE

File Menu: Used to create, open, save and close the project, solution or individual source files.

Edit Menu: Used for text editing and searching in the Visual Studio source code editor.

View Menu: Provides options for setting the visibility of different Visual Studio windows and to switch between code and designer views.

Project Menu: Used for setting different properties of the Visual Studio Project. A Visual Studio project is a collection of files that make up a single assembly or a single object file (we will explore the concept of assemblies in coming lessons).

Build Menu: This menu is used to compile and build the source file, project or solution. The result of a build is an executable file or a code library.

Debug Menu: This menu provides various options related to the Visual Studio.Net Debugger. Debugging is the process of finding logical errors in the program, and a debugger helps make this process easier.

Data Menu: Provides various options for Data Access in .Net

200

Format Menu: Provides access to a set of useful operations for formatting the controls and their layout in the Form Designer view.

Tools Menu: Provides the access to various useful Visual Studio.Net tools.

Using Visual Studio.Net to build the "Hello WinForm" Application

Now we've had a quick tour of Visual Studio.Net, let's use the Visual Studio.Net IDE to build the "Hello WinForm" application which we created earlier in the lesson.

Creating a new Project

First of all, we need to create a new C# Windows Application Project. For this, start Visual Studio.Net and click File'New'Project. It will show the following screen:

From the above screen, select 'Visual C# Projects' in Project types and 'Windows Application' in Templates. Write the name of the new project ('LearningWinForm' in the above figure) in the text box labeled Name. Select the location where you wish to store the project using the Browse... Button and click OK. It will show you an empty form in the designer view similar to the figure below:

In document c# (Page 190-200)