«^»
13.2. Windows Forms applications

The .NET Framework includes a number of classes that can be used to provide an application driven by a GUI. Some of these classes are used in the following program:

namespace WindowsConvert
{
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    public class MyForm : Form
    {
        private TextBox tTextBox;
        private Button tButton;
        private Label tLabel;
        public MyForm()
        {
            tTextBox = new System.Windows.Forms.TextBox();
            tTextBox.Location = new System.Drawing.Point(64, 32);
            tTextBox.Size = new System.Drawing.Size(120, 20);
            Controls.Add(tTextBox);
            tButton = new System.Windows.Forms.Button();
            tButton.Location = new System.Drawing.Point(64, 64);
            tButton.Size = new System.Drawing.Size(120, 20);
            tButton.Text = "Get Fahrenheit";
            tButton.Click += new EventHandler(iHandleClick);
            Controls.Add(tButton);
            tLabel = new System.Windows.Forms.Label();
            tLabel.Location = new System.Drawing.Point(64, 104);
            Controls.Add(tLabel);
            Text = "WindowsConvert";
        }
        protected void iHandleClick(object sender, System.EventArgs e)
        {
            double tCentigrade = double.Parse(tTextBox.Text);
            double tFahrenheit = 32 + tCentigrade*9/5;
            tLabel.Text = tFahrenheit.ToString(); 
        }
        public static void Main() 
        {
            MyForm tMyForm = new MyForm();
            Application.Run(tMyForm);
        }
    }
}

The class MyForm is derived from System.Windows.Forms.Form. Its constructor creates a TextBox object, a Button object and a Label object. It adds each of these to the Controls property of the Form.

A Button object has an Event property called Click and MyForm's constructor uses += to add a method called iHandleClick to the list of methods awaiting a click of the button.

When the button is clicked, the iHandleClick method is executed. This takes the string stored in the TextBox, converts it to a double, produces the corresponding value in Fahrenheit, and stores this as a string in the Label.

The class MyForm has a Main method. When this program is run, it creates a MyForm object and passes this an argument to Application's Run method. The program will terminate when the close button of the form is clicked.

Although it is possible to produce the above program using any text editor, Visual Studio.NET has a wizard that can be used to generate a Windows Forms application. If this is used, you can generate the program by dragging a TextBox, a Button and a Label from the ToolBox onto the form and then adding the C# code to respond to a click of the button. Although the code Visual Studio.NET generates is more verbose than that given above, most of it is reasonably easy to understand.