Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# ПІДРУЧНИКИ / c# / Manning - Windows.forms.programming.with.c#.pdf
Скачиваний:
108
Добавлен:
12.02.2016
Размер:
14.98 Mб
Скачать

1.1.6Program execution

Before we leave this section, let’s review what we’ve learned about how our program executes within the operating system. Run the MyForm.exe program again to see this in action. When you execute this program, the Windows operating system creates and initializes a process that:

1Uses the Main method as the entry point for execution, which:

a Instantiates an instance of the class MyForm using the new keyword, which b Invokes the instance constructor for MyForm, which

c Assigns the string “Hello Form” to the title bar.

2Back in our Main method, the Application.Run method is called with the

newly created MyForm object as a parameter, and:

aDisplays MyForm as the application window, and

bWaits for and processes any messages or user interactions that occur.

3When the application window closes:

a The Application.Run method returns, and b The Main method returns, and

c The program exits.

And that is how it is done in the world of .NET.

1.2Adding controls

Let’s make our program a little more interesting by adding some controls. Throughout the course of the book, we will be building a photo viewing application, so let’s add a button for loading an image file, and a box where the image can be displayed. When we are done, our form will look like figure 1.3.

Figure 1.3

The main window shown here contains a Load button and a picture box control.

Revise your code as shown in listing 1.2. Changes from our previous code listing are shown in bold. Note that we have changed the version number of our program to 1.2

ADDING CONTROLS

13

to distinguish it from our original code and to match the current section. This new version number is also displayed on the title bar. In chapter 2 we will see how to obtain the application’s version number programmatically. For now, changing it by hand will do just fine.

Listing 1.2 A Button and PictureBox control are added to the form

[assembly: System.Reflection.AssemblyVersion("1.2")]

namespace MyNamespace

{

using System;

using System.Windows.Forms;

public class MyForm : Form

{

private Button btnLoad; private PictureBox pboxPhoto;

public MyForm()

{

this.Text = "Hello Form 1.2";

//Create and configure the Button btnLoad = new Button(); btnLoad.Text = "&Load"; btnLoad.Left = 10;

btnLoad.Top = 10;

//Create and configure the PictureBox pboxPhoto = new PictureBox(); pboxPhoto.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; pboxPhoto.Width = this.Width / 2; pboxPhoto.Height = this.Height / 2;

pboxPhoto.Left = (this.Width - pboxPhoto.Width) / 2; pboxPhoto.Top = (this.Height - pboxPhoto.Height) / 2;

//Add our new controls to the Form this.Controls.Add(btnLoad); this.Controls.Add(pboxPhoto);

}

public static void Main()

{

Application.Run(new MyForm());

}

}

}

Compile this program as before and run it to see our changes. We will walk through these changes one at a time.

14

CHAPTER 1 GETTING STARTED WITH WINDOWS FORMS

1.2.1Shortcuts and fully qualified names

The first change you may notice in our new code is the using keyword at the begin-

ning of the program.

using System;

using System.Windows.Forms;

Programmers are always looking for shortcuts; and older programmers, some would say more experienced programmers, often worry that their lines may be too long for the compiler or printer to handle. The programmers at Microsoft are no exception, so while one team probably agreed that fully-qualified names are a good idea, another team probably sought a way to avoid typing them. The result is the using keyword.

The using keyword actually plays two roles in C#. The first is as a directive for specifying a shortcut, as we are about to discuss. The second is as a statement for ensuring that non-memory resources are properly disposed of. We will discuss the using keyword as a statement in chapter 6.

As a directive, using declares a namespace or alias that will be used in the current file. Do not confuse this with include files found in C and C++. Include files are not needed in C# since the assembly incorporates all of this information, making the /reference switch to the compiler sufficient in this regard. This really is just a shortcut mechanism.

In our original program in section 1.1, the Main function called the method

System.Windows.Forms.Application.Run. In our new listing the using directive allows us to shorten this call to Application.Run. The long form is called the fully qualified name since the entire namespace is specified. Imagine if you had to use the fully qualified name throughout your code. Aside from tired fingers, you would have long, cluttered lines of code. As a result, our new code is a bit easier to read:

public static void Main()

{

Application.Run(new MyForm());

}

Since Application is not a C# keyword or a globally available class, the compiler searches the System and System.Windows.Forms namespaces specified by the using directive in order to locate the System.Windows.Forms.Application class.

You can also specify an alias with the using keyword to create a more convenient representation of a namespace or class. For example,

using WF-alias = System.Windows.Forms

With this alias defined, you can then refer to the Application class as

WF-alias.Application.Run(new MyForm());

ADDING CONTROLS

15

Sys-

Alternatively, an alias for a specific type can be created. For example, a shortcut for the Application class can be defined with:

using MyAppAlias = System.Windows.Forms.Application

This would permit the following line in your code:

MyAppAlias.Run(new MyForm());

Typically, the using directive simply indicates the namespaces employed by the program, and this is how we use this directive in our program. For example, rather than the fully qualified names System.Windows.Forms.Button and tem.Windows.Forms.PictureBox, we simply use the Button and PictureBox names directly.

It is worth noting that there is also a Button class in the System.Web.UI.WebControls namespace. The compiler uses the correct System.Windows.Forms.Button class because of the using keyword, and because the System.Web namespace is not referenced by our program.

When we look at Visual Studio .NET in chapter 2, you will see that Visual Studio tends to use the fully qualified names everywhere. This is a good practice for a tool that generates code to guarantee that any potential for ambiguity is avoided.

1.2.2Fields and properties

Let’s go back to our use of the Button and PictureBox classes. The top of our class now defines two member variables, or fields in C#, to represent the button and the picture box on our form. Here, Button and PictureBox are classes in the Windows Forms namespace that are used to create a button and picture box control on a

Form. We will tend to use the terms class and control interchangeably for user interface objects in this book.3

public class MyForm : Form

{

private Button btnLoad;

private PictureBox pboxPhoto;

Fields, like all types in C#, must be initialized before they are used. This initialization occurs in the constructor for the MyForm class.

public MyForm()

{

// Create and configure the Button btnLoad = new Button(); btnLoad.Text = "&Load"; btnLoad.Left = 10;

btnLoad.Top = 10;

3Or, more formally, we will use the term control to refer to an instance of any class derived from the

Control class in the System.Windows.Forms namespace.

16

CHAPTER 1 GETTING STARTED WITH WINDOWS FORMS

// Create and configure the PictureBox pboxPhoto = new PictureBox();

pboxPhoto.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; pboxPhoto.Width = this.Width / 2;

pboxPhoto.Height = this.Height / 2;

pboxPhoto.Left = (this.Width - pboxPhoto.Width) / 2; pboxPhoto.Top = (this.Height - pboxPhoto.Height) / 2;

. . .

Note the use of the new keyword to initialize our two fields. Each control is then assigned an appropriate appearance and location. You might think that members such as Text, Left, BorderStyle, and so on are all public fields in the Button and PictureBox classes, but this is not the case. Public member variables in C++, as well as in C#, can be a dangerous thing, as these members can be manipulated directly by programmers without restrictions. A user might accidentally (or on purpose!) set such a variable to an invalid value and cause a program error. Typically, C++ programmers create class variables as protected or private members and then provide public access methods to retrieve and assign these members. Such access methods ensure that the internal value never contains an invalid setting.

In C#, there is a class member called properties designed especially for this purpose. Properties permit controlled access to class fields and other internal data by providing read, or get, and write, or set, access to data encapsulated by the class. Examples later in the book will show you how to create your own properties. Here we use properties available in the Button and PictureBox classes.4

We have already seen how the Text property is used to set the string to appear on a form’s title bar. For Button objects, this same property name sets the string that appears on the button, in this case “&Load.” As in previous Windows programming environments, the ampersand character ‘&’ is used to specify an access key for the control using the Alt key. So typing Alt+L in the application will simulate a click of the Load button.

Windows Forms controls also provide a Left, Right, Top, and Bottom property to specify the location of each respective side of the control. Here, the button is placed 10 pixels from the top and left of the form, while the picture box is centered on the form.

The Width and Heightproperties specify the size of the control. Our code creates a picture box approximately 1/2 the size of the form and roughly centered within it. This size is approximate because the Width and Height properties in the Form class actually represent the width and height of the outer form, from edge to edge.5

4As we will see in later chapters, the properties discussed here are inherited from the Control class.

5The ClientRectangle property represents the size of the internal display area, and could be used here to truly center the picture box on the form.

ADDING CONTROLS

17

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