Creating a Windows Application in VS.NET using C#

This article has been excerpted from book "The Complete Visual C# Programmer's Guide from the Authors of C# Corner".

Now that you have seen how to create a Windows application from the command line, let's create a Windows application using the VS.NET wizard.

Creating a Skeleton of the Application

Select New->Project->Visual C# Projects->Windows Application from your VS .NET IDE (Figure 9.3).

Fig9.3.gif

Figure 9.3: Creating a Windows Application Project

Press the OK button. The IDE takes you to the Design view of a form as in Figure 9.4.

Fig9.4.gif

Figure 9.4: Design View of a Windows Application.

If the Solution Explorer is not visible, it can be opened from the View menu. The Solution Explorer (see Figure 9.5) provides a list of all available files in your project. The Form1.cs file contains the code for the form and its controls.

Fig9.5.gif

Figure 9.5: Available Classes in a Windows Application Project

To view the code added by the wizard, right-click on Form1.cs and select the View Code menu option as illustrated in Figure 9.6.

Fig9.6.gif

Figure 9.6: View Code Option

The code added by the wizard is discussed in the "Reviewing the Code" section.

Adding Controls

The next step is to add controls to the form. To open the toolbox, choose the View->ToolBox menu item as shown in Figure 9.7.

Fig9.7.gif

Figure 9.7: Toolbox Option

Fig9.8.gif

Figure 9.8: The Toolbox

The toolbox looks like that in Figure 9.8. To add controls to the form, drag a control from the toolbox onto the form and position it anywhere you want. Drag two Button controls and a TextBox, a Label, and a CheckBox control to the form and adjust them so that the form is similar to that shown in Figure 9.9.

Fig9.9.gif

Figure 9.9: Controls on the form in design view

Set the properties of these controls by right-clicking the control and selecting the Properties menu option. The Properties window, shown in Figure 9.10, permits a developer to set design-time properties from within VS.NET. The property list varies, as would be expected, depending on the control type. The design-time values can be considered a control's default values, as they can be changed anytime during the program's execution. A property's value may be changed in two locations. If a value on the property page is altered, that change is reflected in the InitializeComponent method's code, and vice versa a property's value modified in the code is mirrored on the property page by VS.NET.

Fig9.10.gif

Figure 9.10: Properties Window

Set button1's Text property to Set Color and button2's property to Set Font.

Reviewing the Code

Now let's review the code that the Form Designer has written. You can view the code by rightclicking Form1.cs and choosing View Code. The code generated by the wizard appears in Listing 9.3. An instance of the form is created in the Main method as a parameter in the call to Application.Run().

Listing 9.3: Code Added by the Wizard for the Windows Application


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

namespace
Listing9_3App
{
    public class Form1 : System.Windows.Forms.
Form
    {
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.CheckBox checkBox1;
        private System.ComponentModel.Container components = null;

        public Form1()
        {
            InitializeComponent();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }

            base.Dispose(disposing);
        }


        #region
Windows Form Designer generated code

        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.checkBox1 = new System.Windows.Forms.CheckBox();
            this.SuspendLayout();

           
// button1
            this.button1.Location = new System.Drawing.Point(24, 24);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(112, 40);
            this.button1.TabIndex = 0;
            this.button1.Text = "Set Color";

           
// button2
            this.button2.Location = new System.Drawing.Point(160, 24);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(120, 40);
            this.button2.TabIndex = 1;
            this.button2.Text = "Set Font";

           
// textBox1
            this.textBox1.Location = new System.Drawing.Point(32, 104);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(104, 20);
            this.textBox1.TabIndex = 2;
            this.textBox1.Text = "textBox1";

           
// label1
            this.label1.Location = new System.Drawing.Point(176, 104);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(120, 24);
            this.label1.TabIndex = 3;
            this.label1.Text = "label1";

           
// checkBox1
            this.checkBox1.Location = new System.Drawing.Point(120, 168);
            this.checkBox1.Name = "checkBox1";
            this.checkBox1.Size = new System.Drawing.Size(176, 40);
            this.checkBox1.TabIndex = 4;
            this.checkBox1.Text = "checkBox1";

           
// Form1
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(376, 273);
            this.Controls.AddRange(new System.Windows.Forms.Control[]
            { this.checkBox1, this.label1, this.textBox1,

            this.button2, this.button1});
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
        }

        #endregion

        [STAThread]

        static void Main()
        {
            Application.Run(new Form1());
        }
    }
}


The wizard creates a default namespace, Listing9_3App, that bears the same name as the project. It also adds references to various namespaces required by Windows Forms. Note that the Form1 class is derived from System.Windows.Forms.Form. The Dispose method performs any required cleanup of the resources and is called by the runtime when the application closes. The InitializeComponent method creates the Form and all its child controls. In Listing 9.3, the wizard sets the essential control properties and adds the controls to the form via the Controls.AddRange method.

The SuspendLayout and ResumeLayout methods, in the InitializeComponet method, should not be tampered with without a good reason. As the names imply, the methods suspend and resume a layout event, which is triggered whenever a child control must be repositioned or resized. If the layout events are not suspended during the initial window construction, the unnecessary number of events drastically slows the window's creation.

Adding an Event Handler

The last part of this tutorial involves adding an event handler for the Set Font and Set Color buttons. To create an event handler for a button, double-click the button. This generates the required code for a "click" event. Using this method for wiring up an event, the event handler method name will contain same name as the name of the button object. An alternative method is to use the control's Properties window and click the lightning bolt button as demonstrated in Figure 9.11.

Fig9.11.gif

Figure 9.11: Adding an Event Handler for a Button

In Figure 9.11, the button1_Click method is the event handler for that button. If the control is deleted after creating an event handler, the handler method must be manually removed.

Next we create an event handler for button2. Listing 9.4 shows the button1 and button2 click event handlers' code. The button1_Click method uses the ColorDialog class to select a color and set the colors for all controls. The button2_Click method uses the FontDialog class to set the font of all the controls on the form.

Listing 9.4: Button Click Event Handler for Set Font and Set Color Buttons


        private void button1_Click(object sender, System.EventArgs e)
        {
            ColorDialog colorDlg = new ColorDialog();
            colorDlg.ShowDialog();
            textBox1.BackColor = colorDlg.Color;
            label1.BackColor = colorDlg.Color;
            checkBox1.BackColor = colorDlg.Color;
        }


        private void button2_Click(object sender, System.EventArgs e)
        {
            FontDialog fntDlg = new FontDialog();
            fntDlg.ShowColor = true;
            if (fntDlg.ShowDialog() != DialogResult.Cancel)
            {
                textBox1.Font = fntDlg.Font;
                textBox1.ForeColor = fntDlg.Color;
                label1.Font = fntDlg.Font;
                label1.ForeColor = fntDlg.Color;
                checkBox1.Font = fntDlg.Font;
                checkBox1.ForeColor = fntDlg.Color;
            }
        }


Setting Properties at Runtime

We have just shown how to set a control's properties from the Properties window. You can also set the properties programmatically. For example, consider a button's color properties. The background and foreground colors of controls can be changed by using the BackColor and ForeColor properties. The same method for altering color applies to all control properties. They can be set both at designtime and runtime.


button1.BackColor = System.Drawing.Color.Blue;


The Font property of a control allows you to change the font of that control. The Font class of the System.Drawing namespace is used to create a new font. The following code demonstrates how to change the font of a button. Again, the same method for changing fonts applies to all controls.


       button2.Font = new System.Drawing.Font ("Verdana", 10, System.Drawing.FontStyle.Bold);


Building and Running the Project

To run the program press CTRL+F5 or click Start Without Debugging on the Debug menu as shown in Figure 9.12.

Fig9.12.gif

Figure 9.12: Building a Project

Now, run the project and click the Set Color and Set Font buttons. The Set Color button click sets the color of the controls, and the Set Font button sets the font of the controls. The Set Color button calls the ColorDialog class and lets you select a color, as you can see in Figure 9.13.

Fig9.13.gif

Figure 9.13: ColorDialog Dialog Box

The Set Font button event click calls the FontDialog class (see Figure 9.14) and allows the selection of a font as well as its color, style, and size.

Fig9.14.gif

Figure 9.14: FontDialog Dialog Box

Figure 9.15 shows the application after the color and font have been set.

Fig9.15.gif

Figure 9.15: Windows Application Output After Setting Color and Font

Conclusion


Hope this article would have helped you in understanding Creating a Windows Application in VS.NET using C#. See other articles on the website on .NET and C#.

visual C-sharp.jpg
The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.


Similar Articles