Examining the Code of a Windows Program

When you create a new Windows application, the editor shows you a graphical representation of the form, not the form itself. This graphical window is called the Visual Designer. Your program is still based on code. The Designer view simply gives you an alternative way of viewing and modifying the code. To see the underlying code, choose Code Window from the View menu. Figure 6.11 shows the editor displaying the code for the Hello GUI.

Figure 6.11. This code creates the Hello GUI program.


As you scroll through the code, you see that the editor wrote a lot of code. Although the editor writes this automatically, it is not perfect. I’ll show you the automatically generated code and explain what it is doing.

Adding New Namespaces

When you create a console program, the editor presumes that you will want access to the System namespace. In a Windows program, you need access to other namespaces as well. All the visual components are objects, and most of them live in the System.Windows.Forms namespace. Additionally, all the objects used to position controls on a form belong in another important namespace, System.Drawing. When you create a Windows program, the C# editor automatically attaches references to these two critical namespaces, and a few others as well:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

For this simple program, you need not worry about the other namespaces, but it doesn’t hurt to leave them in.

The System.Windows.Forms Namespace

Most of the controls visible on the toolbar are housed in an important namespace, System.Windows.Forms. If you include access to this namespace, your programs can use forms and all the other controls on the Toolbox. Not surprisingly, nearly every Windows-based program uses this namespace. Peruse the object browser or documentation to see all that this namespace has to offer. Be warned, though. The namespace is huge, and you don’t need to memorize all the various elements. It’s just nice to know what’s there. Each of the components is a fullblown object, with properties, methods, and events. To demonstrate some features of the namespace, Figure 6.12 shows the documentation for the Form class.

Figure 6.12. The Form class is a very powerful part of the System. Windows.Forms namespace, with many useful characteristics.


NOTE

IN THE REAL WORLD

Even the pros don’t memorize all these details; they usually have a help screen and keep a reference book around.

You need to know how to dig around and find out the characteristics of components because learning them all is impossible. The more important skill is knowing how to find what you need when you need it. You solve most of your GUI problems by thinking about what kind of component might help. If a control or other object isn’t the solution, a property or method of an object probably is. As you can see, understanding how objects work is the key to modern programming.

Inheritance and Related Components

When you look at the documentation for the Form class, you see that the form object supports a huge number of properties and methods (as well as events, which you’ll investigate shortly). However, the form object is even more powerful than it appears! If you look back at Figure 6.12, you can see a miniature outline showing how the form is related to some other objects. This shows the form object’s family tree. Because the form is a descendant of the ContainerControl class, it has features that enable it to hold other controls. This class is descended from the ScrollableControl class, which is inherited from Control.

Each ancestor of the Form class adds new capabilities to the object. This means that the Form can act just like other controls but also has new features of its own. This is good for you. When you learn which features a Control has, for example, you have a head start on everything that derives from the control object. For example, the Control class has a BackColor property that determines the object’s background color. Because almost all the widgets you can place on a form (and the form itself) have the Control class in their family tree, all of them have access to the BackColor property.

The authors of the .Net framework cleverly used inheritance to simplify their work. (Adding a BackColor property to every component is unnecessary because most components are derived from the Control class, which already has the property.) It also makes your job as a programmer easier. When you understand the inheritance pattern of an object, you know a lot about what it can do. You also have some understanding of unfamiliar components because they usually share characteristics with controls you already know.

The System.Drawing Namespace

Adding a reference to the System.Drawing namespace is necessary because this namespace provides access to certain drawing elements used in the visual designer. Most important of these is the Point class, which is used to determine the size and placement of objects on the screen. The System.Drawing namespace also defines Size and Color. You can look through this namespace in the documentation as well, but most of the classes you find there will not be useful until you have learned how to add event-handling capabilities to your programs.

The Other Namespaces

The editor provides references to other namespaces as well. They are used with enough frequency that the editor puts them in for you. For now, you can safely ignore them, but you will get a chance to play around with some of them later on.

Creating the Form Object

The editor creates all the code necessary to build a basic version of your form. Here is the code that handles basic form creation:

namespace HiGui
{
  /// <summary>
  /// Summary description for Form1.
  /// </summary>

  public class Form1 : System.Windows.Forms.Form
  {
    private System.Windows.Forms.Label label1;
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.Container components = null;

    public Form1()
    {
      //
      // Required for Windows Form Designer support
      //
      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).

NOTE

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.

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

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

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.218.45