{infiniteZest}
// Articles. Tutorials. Utilities.
Home  |   Search  |   Login  
Categories Skip Navigation Links
New / All
AJAX
Apple
ASP.NET
.NET
Git
Google / Android
Python / IronPython
Miscellaneous
SQL Server
First Windows Forms Program in C# Explained
Summary
This article discusses and analyzes the first Windows program created in C#. These programs are also called Smart Clients or Thick Clients or Windows Clients or Windows Forms or WinForms programs.
 
Table of Contents

A New Windows Forms Application

Figure 1. New Project Window for creating Windows Forms Application

Generated Files

Figure 2. The Solution Window of the FirstWindows application

FirstWindows.sln and FirstWindows.suo

FirstWindows.csproj

Code Listing 1. The C# Project File

Form1.cs, Form1.Designer.cs, Program.cs

Miscellaneous Files

Code Analysis

Program.cs

Code Listing 2. Program.cs

Form1.cs and Form1.Designer.cs

Code Listing 3. Form1.cs

Code Listing 4. Form1.Designer.cs

Run the program

Figure 3. Label to display on Form1.

Figure 4. Form with a label

 
Article Series
Previous Article:
Test Your Knowledge: Which one to use: Web Project or Web Site?
This article is part of the Series:
Article Series: First Programs in C# Explained
Next Article:
Test Your Knowledge: First Windows Forms Program in C# Explained

A New Windows Forms Application

In order to create an application that runs on Windows, choose File – New – Project. This opens up the New Project window, as shown in Figure 1.

Figure 1. New Project Window for creating Windows Forms Application

Figure 1. New Project Window for creating Windows Forms Application

As shown in Figure 1, you can create a Smart Client application by choosing the Windows Forms Application template and providing the necessary details like name and location.

If you choose a different .NET Framework version at the top right of the New Project window, then only the templates available for that version will be shown. For example, if you choose .NET Framework version 2.0, then you will not see the WPF related templates (WPF Application, WPF User Control Library, WPF Browser Application, and WPF Custom Control Library). The WPF technology is available in .NET Framework version 3.0 and later.

Generated Files

After you click OK in the New Project dialog box above, Visual Studio will generate a Solution, a Project and several files in it.

Figure 2. The Solution Window of the FirstWindows application

Figure 2. The Solution Window of the FirstWindows application

While the file names are different, you can see lot of similarities in the approach to creating a Web Project with ASP.NET and C#, as discussed in the following article:

First Web Program (Web Project) in C# Explained

Let’s discuss the important files generated for the Windows Application below.

FirstWindows.sln and FirstWindows.suo

We named our application FirstWindows. You will see a Solution file named FirstWindows.sln. This is a text file that contains the information about the projects included in this solution.

If you double-click on the .sln file in the Windows Explorer, it will be opened in Visual Studio, as the .sln files are associated with Visual Studio.

If you go to the root directory of the FirstWindows application, you will also see another file named FirstWindows.suo. This is a binary file – if you open it with Notepad, you will see gibberish (unlike FirstWindows.sln file – which is a readable text file).

This .suo file is specific to the current user using Visual Studio. If you are working in a team environment, this suo file will different for other users (with their own preferences). So, you should not check the .suo file into the Version Control System.

FirstWindows.csproj

FirstWindows.csproj is the project file for this application. Solution file, as discussed above, has a .sln extension and can contain multiple projects. The file with .csproj extension is a C# Project File.

Code Listing 1. The C# Project File

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" ’$(Configuration)’ == ’’ ">Debug</Configuration>
    <Platform Condition=" ’$(Platform)’ == ’’ ">AnyCPU</Platform>
    <ProductVersion>9.0.21022</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{C614FC15-54B1-49FC-9E7A-87A2F60B4FBE}</ProjectGuid>
    <OutputType>WinExe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>FirstWindows</RootNamespace>
    <AssemblyName>FirstWindows</AssemblyName>
    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
  </PropertyGroup>
  <PropertyGroup Condition=" ’$(Configuration)|$(Platform)’ == ’Debug|AnyCPU’ ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" ’$(Configuration)|$(Platform)’ == ’Release|AnyCPU’ ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="System" />
    <Reference Include="System.Core">
      <RequiredTargetFramework>3.5</RequiredTargetFramework>
    </Reference>
    <Reference Include="System.Xml.Linq">
      <RequiredTargetFramework>3.5</RequiredTargetFramework>
    </Reference>
    <Reference Include="System.Data.DataSetExtensions">
      <RequiredTargetFramework>3.5</RequiredTargetFramework>
    </Reference>
    <Reference Include="System.Data" />
    <Reference Include="System.Deployment" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.Windows.Forms" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Form1.cs">
      <SubType>Form</SubType>
    </Compile>
    <Compile Include="Form1.Designer.cs">
      <DependentUpon>Form1.cs</DependentUpon>
    </Compile>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
    <EmbeddedResource Include="Properties\Resources.resx">
      <Generator>ResXFileCodeGenerator</Generator>
      <LastGenOutput>Resources.Designer.cs</LastGenOutput>
      <SubType>Designer</SubType>
    </EmbeddedResource>
    <Compile Include="Properties\Resources.Designer.cs">
      <AutoGen>True</AutoGen>
      <DependentUpon>Resources.resx</DependentUpon>
    </Compile>
    <None Include="Properties\Settings.settings">
      <Generator>SettingsSingleFileGenerator</Generator>
      <LastGenOutput>Settings.Designer.cs</LastGenOutput>
    </None>
    <Compile Include="Properties\Settings.Designer.cs">
      <AutoGen>True</AutoGen>
      <DependentUpon>Settings.settings</DependentUpon>
      <DesignTimeSharedInput>True</DesignTimeSharedInput>
    </Compile>
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>

As you can see in Code Listing 1, the project file is an XML text file. It contains a whole lot of information about the project, including:

  • platform to compile this project to
  • how to generate debug and release binaries
  • the references to other assemblies included in this project
  • the source files that are part of this
  • the commands to run before and after the build

Form1.cs, Form1.Designer.cs, Program.cs

These are the C# files that are generated by Visual Studio. Typically, you will add more logic to Form1.cs file (after changing its name to something appropriate for your project).

The code in these files is discussed in the following section in detail.

Miscellaneous Files

In addition to the above files, several other files are also generated as a part of the solution.

AssemblyInfo.cs

This file contains the information about the assembly (the dll or exe). This information includes assembly title, assembly description, assembly version, assembly copyright, and so on.

Resources.*

These two files (Resources.resx and Resources.Designer.cs) contain resource information – like strings, etc.

Settings.*

These two files (Settings.settings and Settings.Designer.cs) contain the application settings (whether the scope is for user or for application).

Code Analysis

In this section, let’s analyze the code generated as a part of some of the important files in this application.

Program.cs

Code Listing 2. Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace FirstWindows
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

As shown in Code Listing 1, the Program.cs file contains the Main() method. This is the entry point for C# applications. This method uses the Application class from the System.Windows.Forms namespace. The System.Windows.Forms namespace is the main namespace that contains WinForms functionality.

The Application class provides a whole bunch of static methods that help manage an application. The last line in this method calls a method called Run with Form1 as the parameter.

As required in every Windows program, this Run() method starts the main message loop for the application. It also shows the Form1 after that.

Form1.cs and Form1.Designer.cs

Code Listing 3. Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FirstWindows
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    }
}

Code Listing 4. Form1.Designer.cs

namespace FirstWindows
{
    partial class Form1
    {
        /// <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.components = new System.ComponentModel.Container();
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Text = "Form1";
        }

        #endregion
    }
}

The code shown in Code Listings 3 and 4 is the basic code for showing a form/screen in a Windows Forms application.

One of the first things you would do is to change the name of the form from Form1 to something else that is meaningful for your application.

Form1.Designer.cs is where the Visual Studio Form designer will keep adding code as you add more controls to the form. And the Form1.cs is where you write the code.

While you ‘draw’ the user interface on Form1, those controls (like labels, textboxes, buttons, etc.) will be created in code in the InitializeComponent() method in Form1.Designer.cs file.

And, as you can see, this method is called from the constructor of the Form1 class.

Run the program

We will add just one label to the form and set it to: Hello from FirstWindows.

Figure 3. Label to display on Form1.

Figure 3. Label to display on Form1.

Simply drag the Label from the Toolbox and drop it on to the design surface of Form1. Then from the Properties window, set the Text property to Hello from FirstWindows.

If you run the above application (by pressing F5), you will see the window shown in Figure 4 with the label displayed.

Figure 4. Form with a label

Figure 4. Form with a label

Take a Quick Quiz on this Article

1. Which of the following Windows Project Templates are available only in .NET Framework 3.0 (and Visual Studio) and later?



: Windows Presentation Foundation is relatively new.
Question 1 of 11
Article Series
Previous Article:
Test Your Knowledge: Which one to use: Web Project or Web Site?
This article is part of the Series:
Article Series: First Programs in C# Explained
Next Article:
Test Your Knowledge: First Windows Forms Program in C# Explained
Bookmark and Share This

More Articles With Similar Tags
icon-first-web-new-project.jpg
This article explains and dissects the pieces involved in creating the first web program in C# using the Web Project method (as opposed to the Web Site method).
How do you develop an ASP.NET program using the Web Project model?
icon-first-web-site-solution-explorer.jpg
This article explains and dissects the pieces involved in creating the first web program in C# using the Web Site method (as opposed to the Web Program method).
What is involved in developing a web-based program using the C# programming language with Web Site - Solution as the model.
This test has questions on developing first console (shell) based programs using the C# programming language.
About  Contact  Privacy Policy  Site Map