Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft CSharp Programming For The Absolute Beginner (2002) [eng]-1.pdf
Скачиваний:
46
Добавлен:
16.08.2013
Размер:
15.71 Mб
Скачать

InitializeComponent();

//

// TODO: Add any constructor code after InitializeComponent call

//

}

I left this code exactly as it was created in the editor. Of course, you usually modify the code. The program starts with a summary block, where you can add documentation to your form. The code then proceeds with a definition of the Form1 object. The Form1 class is inherited from the System.Windows.Forms.Form class.

The form is a class, and it has a constructor, like any other class. In this case, the constructor is extremely simple. It calls one method, InitializeComponent(). This method is required for all code created with the Designer, and it must be called from your constructor. I’ll show you the code in that method shortly. If you want to add any other constructor code, you add it after the line marked with the TODO comment. If you wish, you can take out the TODO comments altogether, as they are simply a placeholder telling you where to write your code.

Creating a Destructor

The code editor also provides an interesting method named Dispose(). Here is the code for the Dispose() method:

///<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 Dispose() method is automatically called whenever the Form1 class is ready to close (usually at the end of the program).

In the Real World

Dispose() is an example of a destructor method, which is automatically called when a class is no longer needed. The code provided here ensures that the Form class will remove itself from memory when it is no longer needed. In older languages, such as C and C++, it is very important to supply destructors such as the Dispose() method so that your program does not leave pieces of itself in the computer’s memory after it closes. You might notice that after your computer has run for a long time without rebooting, it appears to be more sluggish. Programs that do not clean up after themselves properly are possible culprits. Fortunately, C# provides automatic garbage collection, which automates the process of cleaning up memory. At this stage of your programming career, it’s safe to presume that the automatic garbage collection routines will work properly. Simply leave the Dispose() method alone, and move to the parts of the program that need your attention.

143

Creating the Components

The components are created and added to the form in the InitializeComponent() method (which, like everything else in this section, was automatically created for you by the editor). This method translates the components drawn on the form with the Designer to actual code that will produce the desired results. Take a look at what happens inside the InitializeComponent() method:

#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.label1 =

new System.Windows.Forms.Label(); this.SuspendLayout();

//

// label1

//

this.label1.BackColor = System.Drawing.Color.White;

this.label1.Font =

new System.Drawing.Font( "Glass Gauge", 27.75F,

System.Drawing.FontStyle.Regular,

System.Drawing.GraphicsUnit.Point,

((System.Byte)(0))); this.label1.Location =

new System.Drawing.Point(56, 56); this.label1.Name = "label1"; this.label1.Size =

new System.Drawing.Size(288, 56); this.label1.TabIndex = 0; this.label1.Text = "Hello World!!"; this.label1.TextAlign =

System.Drawing.ContentAlignment.MiddleCenter;

//

// myForm

//

this.AutoScaleBaseSize =

new System.Drawing.Size(5, 13); this.ClientSize =

new System.Drawing.Size(392, 189); this.Controls.AddRange(new

System.Windows.Forms.Control[] {

this.label1}); this.Name = "myForm";

this.Text = "Hello, World!"; this.ResumeLayout(false);

}

#endregion

144

This method creates the label object (and any controls you add to a form) and sets the properties of all controls and the form. (Note that label1 ends with a numeral 1, not two ls.) There are a couple things to notice about the method. First, the SuspendLayout() and ResumeLayout() methods are used to suspend drawing until all the objects are configured and then to draw them all at once. Second, the comments tell you that this method was generated by the Designer and that you should not modify it by hand. This is generally good advice. You should think twice about modifying code in the InitializeComponent() method. If you do modify the code, the Designer might not recognize your changes, and the program will no longer function correctly.

Setting Component Properties

Components are objects, and like all objects, they have properties. The visual designer makes it very easy to set up an object and its properties. Because many component properties are visual in nature, you often can see the results of your property manipulation as you are editing the object, before your program even runs. As an example, here is the part of the method that sets up label1:

this.label1 =

new System.Windows.Forms.Label(); this.SuspendLayout();

//

// label1

//

this.label1.BackColor = System.Drawing.Color.White;

this.label1.Font = new System.Drawing.Font( "Glass Gauge", 27.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));

this.label1.Location =

new System.Drawing.Point(56, 56); this.label1.Name = "label1"; this.label1.Size =

new System.Drawing.Size(288, 56); this.label1.TabIndex = 0; this.label1.Text = "Hello World!!"; this.label1.TextAlign =

System.Drawing.ContentAlignment.MiddleCenter;

//

After the method creates a new instance of the Label class, label1., it sets properties of the label. Essentially, the program looks at the label on the form and the label’s properties and sets all the properties of the label1 class so that it matches the label on the Designer. Some of the properties are designed to hold special kinds of data. For example, label1.Size requires a value of type System.Drawing.Size. Many of the property values are related to the System.Drawing namespace. For example, you can specify the color white as System.Drawing.Color.White. Most of the time, you don’t have to worry about the specifics, but sometimes you need to know what kind of information goes into a property. Looking at the code generated by the Designer can be a good clue.

Setting Up the Form

The form itself is a component and is set up much like the label:

//

// myForm

//

this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

145

this.ClientSize = new System.Drawing.Size(392, 189); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.label1});

this.Name = "myForm"; this.Text = "Hello, World!"; this.ResumeLayout(false);

The AutoScaleBaseSize property is used to set up how the form should be automatically scaled, based on the current font if the user decides to change the size of the form. You won’t have to create it yourself. The ClientSize property determines how much room the form will have for controls. The Name and Text properties are straightforward.

The line this.Controls.AddRange(...) sets up a place in memory to hold all the controls that will be on the form. At this point, only one control is on the form, the label. If the form were more complex, each of the controls on the form would show up in a list inside this command. The AddRange() method allows you to add several controls to the form. Adding a control to a form is actually a two−step process. You designate the size, position, and other properties of the control. Then you use the AddRange() method (or another control−adding method) to create the logical link between the form and the control. Both functions are handled automatically by the Designer. (Again, I’m just showing you what is happening under the hood.)

Writing the Main() Method

Because this program is meant to stand alone, it must have a Main() method. Throughout this example, the Designer has automatically generated all the code. The Main() method is no different. Recall that the Main() method usually does nothing more than instantiate an object. The Main() method created by the Designer does the same thing but in a slightly different manner than you have seen.

///<summary>

///The main entry point for the application.

///</summary>

[STAThread] static void Main()

{

Application.Run(new Form1());

}

The [STAThread] directive defines the default threading model for the application. Threaded programs determine how your programs will behave when other programs are running in the same system. For now, leave the STAThread line alone. This setting is fine for your current needs.

The Main() method has only one line in it and simply instantiates the Form1 object. You can use the Run method of the Application object to run any class in your namespace that has a Main() method. This works much the same as the technique you learned in the preceding chapter (creating a local variable and instantiating the class to that variable). However, because the editor created this code, it’s best to leave this alone.

Trap If you change the name of the default form, be sure to check that the Application.Run() call in the Main() method points to the new form name. The Run() method does not automatically change, and the program will not run. Change the code to reflect your new form name, and you’ll have no problems. This is an example of why you need to know what the Designer is doing—it isn’t perfect.

146

Соседние файлы в предмете Программирование на C++