Get up to 80 % extra points for free! More info:

Lesson 1 - Introduction to Windows Forms applications

Welcome to the first lesson of the course, where we'll learn how to create form (window) applications in C# .NET and try using individual components. We'll work with buttons, text fields, tables, but also with images, timers and other controls available in these applications.

I wrote the course so that you don't need any advanced knowledge. I assume, however, that you know at least the basics of object-oriented programming.

Windows Forms

Windows Forms is the first framework from .NET that allows creating form applications easily using a graphic designer. We can find there a full set of ready-made controls (sometimes referred to as components) for most situations. And if we wouldn't be satisfied with them, we can of course create our own or modify an existing one. It's Windows Forms that we're going to focus on in this course.

Currently there's one more modern framework - WPF (Windows Presentation Foundation) along with WinForms. It separates logic and the user interface better, supports faster rendering, animations, bindings, and other new technologies. In practice, both frameworks are used to build form applications, newer applications use WPF, existing applications mostly use WinForms. Currently, WinForms isn't marked as obsolete and is still in use, its use is simple and you'll surely encounter many applications written in WinForms. So you should at least be aware of them, although it's certainly better to create new applications in WPF, which is technologically much further.

Our First Form Application

We won't start with anything other than the classic Hello World application, this time in forms :) If you haven't read local course, let me repeat that it's a simple application that does nothing but write some text.

Create a new project, select Windows Forms Application as the project type. Type HelloForms as the project name:

Creating a new Windows Forms project in Visual Studio - Form Applications in C# .NET Windows Forms

Your Visual Studio window should now look something like this:

Windows Forms application in Visual Studio - Form Applications in C# .NET Windows Forms

Let's describe its individual parts, which we'll use to develop form applications. Important parts are highlighted in red in the image above.

  • Designer - In the Designer we see what the form looks like. So far, it's just an empty window.
  • Properties - In the Properties window, we can see the properties of the currently selected element on the form. If you don't see the window, enable it in View -> Properties Window.
  • Toolbox - Toolbox is a sliding window that serves as a palette with individual controls that we can add to the form.

Setting control properties

When we select an element on the form or the form itself, we can change the properties of that element in the Properties window.

Since we got no element on the form, it's the form what is selected. We'll change the title to "Hello". Find the Text property and enter Hello in it. The result is reflected in the designer immediately. This way we'll set the properties of all elements on the form.

Adding Controls to the Form

Now we'll open the Toolbox and select the Label control, which is a text label. We'll insert it into the form either by double-clicking on it or by dragging it. Reduce the form size and simply drag the label in the middle. In the Properties window, set the label to "Hello from forms".

As always, you can start your first window application with the green Play button or the F5 key. You should get a similar result:

The first window application in C# .NET - Form Applications in C# .NET Windows Forms

Under the Hood

Let's explain how the application works inside. The form itself is of course an object (how else :) ). It's declared as the Form1 class which we can find in the Form1.cs file. Of course you can rename the file in Solution Explorer, the class will also be renamed. For our application, the form could be named HelloForm, rename it so you can navigate in it better.

Visual Studio displays either a visual preview of the form or its source code. We can switch between these modes either by right-clicking on the form (resp. on the code) and selecting View Code (resp. View Designer). It's useful to know the keyboard shortcuts Shift + F7 to move to the designer and Ctrl + Alt + 0 to move to the code. It must be the zero on the alphanumeric keyboard (the left one).

Move to form code that looks like this (I omitted the initial using statements):

namespace HelloForms
{
    public partial class HelloForm : Form
    {
        public HelloForm()
        {
            InitializeComponent();
        }
    }
}

We can see that the form is a class inherited from the Form class. We can't see any trace of anything we added or set to the form, only the constructor calls the strange InitializeComponent() method.

The class is marked as partial, meaning it's defined in multiple files. Specifically, there's also a HelloForm.Designer.cs file that contains less readable code that is automatically generated by us clicking in the designer.

This code is separated into another file on purpose, to make the form's source code clear. Never tamper with the Designer.cs file manually, you even wouldn't have to know that it exists. But let's look at its content to understand how the application works:

namespace HelloForms
{
    partial class HelloForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #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.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(75, 32);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(135, 17);
            this.label1.TabIndex = 0;
            this.label1.Text = "Hello from forms";
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(282, 80);
            this.Controls.Add(this.label1);
            this.Name = "Form1";
            this.Text = "Helloz";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
    }
}

In the code, we see the hidden InitializeComponent() method, which does nothing but create all the elements on the form one by one and set the appropriate properties we've chosen. Here we can see how our label is created and its properties set. The method is then called in the constructor to initialize the form. An unaware programmer is then completely encapsulated from the code that the designer generates. Of course, this is mainly to prevent them from breaking it :) However, it's important to know how it works to be able to, for example, add controls at runtime or fix errors in the designer file.

Today's project can be downloaded in the article's attachment, including the source code, and it'll always be like this. If you had any problems, you can easily find your mistake like this. In the next lesson, Simple Calculator in C# .NET Windows Forms, we'll explain how events work and program a simple calculator.


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 44x (199.27 kB)
Application includes source codes in language C#

 

All articles in this section
Form Applications in C# .NET Windows Forms
Skip article
(not recommended)
Simple Calculator in C# .NET Windows Forms
Article has been written for you by David Capka Hartinger
Avatar
User rating:
9 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities