Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Лаба №1 / books / csharp_ebook.pdf
Скачиваний:
77
Добавлен:
03.03.2016
Размер:
3.69 Mб
Скачать

Programmers Heaven: C# School

10. WinForms & Windows Applications

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.

190

Programmers Heaven: C# School

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

191

Programmers Heaven: C# School

}

}

}

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

{

192

Programmers Heaven: C# School

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.

193

Programmers Heaven: C# School

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

194

Programmers Heaven: C# School

}

}

}

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.

195

Соседние файлы в папке books