Setting and Adding Properties to a Windows Form

Create a Windows form by using the Windows Forms Designer:

  • Add and set properties on a Windows form.

The properties of an object provide a mechanism through which objects can expose their characteristics to the external world. In the following sections you will learn how to customize a form's appearance by using its properties. You will also learn how you can add your own properties to a form.

Using the Visual Designer to Set Windows Form Properties

A Windows form derives from several other classes, such as Object, Control, and so on, through a chain of inheritances. As a result of this inheritance, the Windows form inherits the properties of its parent classes in addition of its own specific properties. All these properties are available for easy manipulation through the Properties window in Visual Studio .NET. Step by Step 1.4 shows you how to manipulate some of these properties to get a feel for how they affect the behavior of a form.

STEP BY STEP

1.4 Working with Windows Form Properties

1.
Open the project 316C01. In the Solution Explorer right-click the project name and select Add, Add Windows Form from the context menu. Name the new form StepByStep1_4.

2.
Right-click the form and select Properties from the context menu. Find the BackColor property and click the down arrow of the drop-down list. This invokes a tabbed list of colors in which three categories of colors are available: Custom, Web, and System. Click the tab titled Web and select AntiqueWhite from the list. Note that the form's surface immediately changes color to reflect this property change.

3.
In the Properties window, locate the property named FormBorderStyle and change its value from Sizable to FixedSingle.

4.
In the Properties window, look for the property named Size. Expand this property by clicking the + sign next to it. Change the Width subproperty to 400 and the Height subproperty to 200.

5.
Go to the StartPosition property in the list of properties and change its value to CenterScreen.

6.
Change the MinimizeBox property to False.

7.
Right-click anywhere on the form and select View Code from the context menu. In the code view, insert the following code just after the Windows Form Designer Generated Code region:

[STAThread]
static void Main()
{
    Application.Run(new StepByStep1_4());
}

8.
In the Solution Explorer, right-click the project name and select Properties from the context menu. In the Property Pages window, set _316C01.StepByStep1_4 as the startup object. Click OK to close the Property Pages window.

9.
Select Debug, Run. The application displays the form, showing the effect of the property settings that you made. The result looks similar to that shown in Figure 1.12.

Figure 1.12. You can change a form's properties—such as BackColor, Size, and FormBorderStyle—to customize its appearance.



In Step by Step 1.4, you manipulate various properties of a form to change its visual appearance. When you invoke the Properties window for the form, you see a big list of properties that are available to you. These properties provide significant control over the characteristics of the form. Table 1.5 lists some of the important properties of the Form class.

Table 1.5. Some Important Properties of the Form Class
Property NameDescription
BackColorSpecifies the background color of the form
BackgroundImageSpecifies the background image displayed in the form
ClientSizeSpecifies the size of the client area of the form
ControlBoxIndicates whether a control box needs to be displayed in the caption bar of the form
DesktopLocationSpecifies the location of the form on the Windows desktop
EnabledIndicates whether a control can respond to user interaction
FormBorderStyleSpecifies the border style of the form
HandleGets the Window Handle (HWND) of the form
HelpButtonIndicates whether a Help button is to be displayed on the caption bar of the form
IconSpecifies the icon for the form
MaximizeBoxIndicates whether a maximize button is to be displayed on the caption bar of the form
MaximumSizeSpecifies the maximum size to which the form can be resized
MinimizeBoxIndicates whether a minimize button is to be displayed in the caption bar of the form
MinimumSizeSpecifies the minimum size to which the form can be resized
ModalIndicates whether the form is to be displayed modally
NameSpecifies the name of the form
OpacitySpecifies the opacity level of the form
ShowInTaskbarIndicates whether the form is to be displayed in the Windows taskbar
SizeSpecifies the size of the form
StartPositionSpecifies the starting position of the form at runtime
TopMostIndicates whether the form should be displayed as the topmost form of the application

The properties in Table 1.5 have various data types. You will find that some properties, such as FormBorderStyle, are enumeration types; some properties, such as Size, are of type struct, and their values are determined by the values of their contained members (for example, X and Y); other properties, such as MinimizeBox, accept a simple Boolean value. The Properties window provides a nice user interface for working with these values.

To increase your understanding about what's going on behind the scenes, it would be a good idea to switch to the code view, expand the Windows Form Designer Generated Code region, and analyze the generated code.

Setting Windows Form Properties Programmatically

Using the Windows Forms Designer is a quick and easy way to manipulate control properties, but the designer can only set the properties at design time. What would you do if wanted to change the appearance of a form at runtime? You could write your own code in the code view. In complex projects, as you need more functionality in an application, you will find yourself switching frequently to the code view. Sometimes you can learn a lot about the .NET Framework by using the code view because it gives you an opportunity to directly play with .NET Framework data structures.

Step by Step 1.5 lets you explore some more properties of a Windows form and programmatically code the properties that are used in Step by Step 1.4. Step by Step 1.5 also shows you how to create a form programmatically.

STEP BY STEP

1.5 Setting Windows Form Properties Programmatically

1.
Open the project 316C01. In the Solution Explorer right-click the project name and select Add, Add Windows Form from the context menu. Name the new form StepByStep1_5.

2.
Right-click anywhere on the form and select View Code from the context menu. In the code view, insert the following code just after the Windows Form Designer Generated Code region:

[STAThread]
static void Main()
{
    // Create StepByStep1_5 object
    // and set its properties
    StepByStep1_5 frm1_5 = new StepByStep1_5();
    frm1_5.BackColor = Color.AntiqueWhite;
    frm1_5.FormBorderStyle =
        FormBorderStyle.FixedSingle;
    frm1_5.Size = new Size(400,200);
    frm1_5.StartPosition =
       FormStartPosition.CenterScreen;
    frm1_5.MinimizeBox = false;
    Application.Run(frm1_5);
}

3.
In the Solution Explorer, right-click the project name and select Properties from the context menu. In the Property Pages window, select _316C01.StepByStep1_5 as the startup object. Click OK to close the Property Pages window.

4.
Select Debug, Run. The form that is displayed looks similar to the form that you created in Step by Step 1.4 (refer to Figure 1.12).


In Step by Step 1.5, when you add a new Windows form to a project, a new class representing that form is created. As you can see in the code in Step by Step 1.5, you first create an object of the class so that you can later modify the object's properties. The modified form object is then passed as a parameter to the Application.Run() method that invokes the form.

While you are typing code in the code view, you see Visual Studio .NET helping you with the properties and syntaxes via IntelliSense. You should also note that values for properties such as BackColor and FormBorderStyle are encapsulated in enumerated types. You can find out what enumerated type to use for a property by hovering your mouse pointer over a property name in the code view. This displays a ToolTip that helps you identify the type of a property.

NOTE

Leaving the Autogenerated Code Alone The Windows Forms Designer manages the InitializeComponent() method. Putting your own code within that method might interfere with the designer's working. It is therefore generally recommended that you avoid modifying this method.


If you compare the code that you write manually in Step by Step 1.5 with the code that is generated by the Windows Forms Designer in Step by Step 1.4, you should see that the most significant difference is that the designer includes all its code for setting form properties in the InitializeComponent() method.

You can alternatively place the code inside the form's constructor after the call to the InitializeComponent() method. Including the code in the constructor ensures that the code is executed every time an instance of the form is created. The effect in this case would be the same as the effect of placing the code in the InitializeComponent() method.

So far you have seen how to get and set properties for a Windows form. The Form class also provides a set of methods, and Step by Step 1.6 demonstrates how to use them.

STEP BY STEP

1.6 Invoking Methods of Windows Forms

1.
Open the project 316C01. In the Solution Explorer right-click the project name and select Add, Add Windows Form from the context menu. Name the new form StepByStep1_6.

2.
Right-click anywhere on the form and select View Code from the context menu. In the code view, insert the following code just after the Windows Form Designer Generated Code region:

[STAThread]
static void Main()
{
    // Create StepByStep1_6 object
    // and set its properties
    StepByStep1_6 frmBottom = new StepByStep1_6();
    frmBottom.BackColor = Color.AntiqueWhite;
    frmBottom.FormBorderStyle =
        FormBorderStyle.FixedSingle;
    frmBottom.Size = new Size(400,200);
    frmBottom.StartPosition =
       FormStartPosition.CenterScreen;
    frmBottom.MinimizeBox = false;

    // Create a new form and set its
    // properties to stay on top
    Form frmOnTop = new Form();
    frmOnTop.TopMost = true;
    frmOnTop.Opacity = 0.7;
    frmOnTop.Show();

    Application.Run(frmBottom);
}

NOTE

The Opacity Property Transparent forms are supported only on operating systems that can display layered windows. Such operating systems include Windows 2000, Windows XP and later versions of Windows. The Opacity property has no effect when you run a program on older operating systems such as Windows 98.

3.
In the Solution Explorer, right-click the project name and select Properties from the context menu. In the Property Pages window, select _316C01.StepByStep1_6 as the startup object. Click OK to close the Property Pages window.

4.
Select Debug, Run. The application displays two forms. The top form is transparent and stays on the top, even when you click the other form (see Figure 1.13).

Figure 1.13. The Show() method sets the Visible property of a form to true.



EXAM TIP

Form.Close() Versus Form.Hide() When you close a form by using its Close() method, all resources related to that form are released. You cannot call the Show() method to make the form visible again because the form itself does not exist anymore. If you want to temporarily hide a form and show it at a later time, you can use the form's Hide() method. Using the Hide() method is equivalent to setting the form's Visible property to false. The form still exists in memory, and you can make it visible any time by calling the Show() method of the form or by setting the form's Visible property to true.


In Step by Step 1.6 you create a new form by creating an instance of the Form class. You set the properties of the new form so that it is the topmost form in the application and then you reduce the opacity to make the form slightly transparent. Finally, you invoke the Show() method of the form to actually display the form onscreen.

There are two forms in Step by Step 1.6, but you are calling the Show() method for only one of them. When you run the program, you actually see both forms onscreen. How? It happens because frmBottom is passed as a parameter to the Application.Run() method. When the Application.Run() method starts the application by launching frmBottom onscreen, in the process it internally calls the Show() method for frmBottom. In the running program, if you close frmOnTop, you close just that form, but if you close frmBottom, you close all open forms and quit the application.

GUIDED PRACTICE EXERCISE 1.1

You are a Windows developer for SpiderWare, Inc. In one of your applications you are required to create a form that enables users to set various options of the application. You want the form to have the following characteristics:

  • It should have a thin title bar showing the text Options and a close button. The user should not be able to resize, minimize, or maximize this form.

  • It should always appear on top of the other forms in the application.

  • It should be always displayed in the center of the screen.

How would you create such a form?

You should try working through this problem on your own first. If you get stuck, or if you'd like to see one possible solution, follow these steps:

1.
Open the project 316C01. Add a Windows form with the name GuidedPracticeExercise1_1 to the project.

2.
Open the Properties window for the form. Change the value of the Text property to Options.

3.
Change the FormBorderStyle property to FixedToolWindow.

4.
Change the StartPosition property to CenterScreen.

5.
Change the TopMost property to true.

6.
Switch to the code view, and insert the following Main() method:

[STAThread]
static void Main()
{
    Application.Run(new GuidedPracticeExercise1_1());
}

7.
Set the form as the startup object and execute the program.

If you have difficulty following this exercise, review the section “Designing a Windows Form by Using Windows Forms Designer,” earlier in this chapter. Also spend some time looking at the various properties that are available for a form in the Properties window. Experimenting with them in addition to reading the text and examples in this chapter should help you relearn this material. After doing that review, try this exercise again.


Adding New Properties to a Windows Form

In addition to using the existing properties, you can add custom properties to a Windows form. You can use a custom property to store application-specific data.

STEP BY STEP

1.7 Adding New Properties to a Windows Form

1.
Open the project 316C01. In the Solution Explorer right-click the project name and select Add, Add Windows Form from the context menu. Name the new form StepByStep1_7.

2.
Right-click anywhere on the form and select View Code from the context menu. In the code view, insert the following code just after the Windows Form Designer Generated Code region:

//define constant values for State
public enum State{Idle, Connecting, Processing}

//use this field as storage location
//for FormState property
private State formState;

//set attributes for FormState property
[Browsable(true),
EditorBrowsable(EditorBrowsableState.Never),
Description("Sets the custom Form state"),
Category("Custom")]

//Creating FormState property
public State FormState
{
    get
    {
        return formState;
    }
    set
    {
        formState = value;
        switch (formState)
        {
            case State.Idle:
                this.BackColor = Color.Red;
                this.Text = "Idle";
                break;
            case State.Connecting:
                this.BackColor = Color.Orange;
                this.Text = "Connecting...";
                break;
            case State.Processing:
                this.BackColor = Color.Green;
                this.Text = "Processing";
                break;
        }
    }
}

3.
Change the form's constructor so that it looks like this:

public StepByStep1_7()
{
    // Default code of the Constructor
    //set the FormState property of this form
    this.FormState = State.Processing;
}

4.
Add the following Main() method to the form:

[STAThread]
public static void Main()
{
    Application.Run(new StepByStep1_7());
}

5.
In the Solution Explorer, right-click the project name and select Properties from the context menu. In the Property Pages window, select _316C01.StepByStep1_7 as the startup object. Click OK to close the Property Pages window.

6.
Select Debug, Run. The project shows a green-colored form onscreen.


The most important thing to note in Step by Step 1.7 is that you add a custom property named FormState to a form. The property that you create is even visible in the IntelliSense list when you try to access the members of this form object by typing a period (.) after the form's name in the form's constructor code.

To a program that uses the properties, the properties in Step by Step 1.7 look just like data fields, but properties by themselves do not have any storage locations, and their definitions look almost like method definitions. Properties provide two accessors (get and set) that would be called when a program would like to read from or write to the property. In Step by Step 1.7 you use a private field formState that works as a storage location for the FormState property; because formState is private, the rest of the world can access it only through the FormState public property. The data type of FormState is the enumerated type State, defined with a limited set of named constant values at the beginning of the code segment.

EXAM TIP

Read-Only and Write-Only Properties The get and set accessors allow both read and write access to a property. If you want to make a property read-only, you should not include a set accessor in its property definition. On the other hand, if you want a write-only property, you should not include a get accessor in the property definition.


If you go to the design view and inspect the properties of form StepByStep1_7 through Properties window, you will not find the FormState property listed along with other properties. This is because the Properties window shows only the properties of the base class. You can think of it like this: The Properties window helps you design a new class (StepByStep1_7) in terms of a class that already exists (System.Windows.Forms.Form). So while you are designing the StepByStep1_7 class, if the Properties window would rather show the properties of the StepByStep1_7 class, then it's similar to defining a class in terms of a class that is itself under construction.

NOTE

Using the get and set Accessors Accessors of a property can contain executable statements. The code contained in the get accessor executes when a program reads the value of a property. Similarly, when a program writes a value to a property, it executes the set accessor of the property.


If you instead define a form by using the completely created class StepByStep1_7, it would make sense to have the FormState property available in the derived form through the Properties window. (I talk about this in a moment.)

Note that the FormState property has a big list of attributes. Such a big list isn't required to create a property, but it helps you specify the runtime behavior of the property. Table 1.6 describes how attributes can control the behavior of a property.

Table 1.6. Attributes That Control the Behavior of a Property
Attribute NameDescription
BrowsableIndicates whether the property is displayed in the Properties window. Its default value is true.
EditorBrowsableIndicates whether the property should appear in the IntelliSense list of an object in the code view. Its value is of the EditorBrowsableState enumeration type, with three possible values—Advanced, Always, and Never. Its default value is Always, which means “always list this property.” If you change the value to Never, the property is hidden from the IntelliSense feature.
DescriptionSpecifies a description string for the property. When the Description property is specified, it is displayed in the description area of the Properties window when the property is selected.
CategorySpecifies the category of the property. The category is used in the Properties window to categorize the property list.

You cannot see the effect of using the attributes listed in Table 1.6 in the form you have been creating. However, you would see their effects if you inherited a form from that form. You'll learn more about this in the next section of this chapter.

REVIEW BREAK

  • Properties let you customize the appearance and behavior of a Windows form.

  • The Windows Forms Designer lets you define a form based on the properties that are available in its base class (which is usually the Form class).

  • You can add custom properties to a form.

  • Attributes let you define the runtime behavior of a property.


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

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