Monday, August 25, 2008

Introduction to Winforms

WinForms is a programming model used to create Windows Applications. .NET framework offers base classes for building Windows applications. Most of the functionality for these classes is in the System.Windows.Forms namespace. The Visual Studio is used to design these applications visually, and to automatically generate the code.

Hello World

Lets look at the simplest traditional �hello world� example which will help us create our first Windows application in C#.

Click on the File menu and select New | Project. Now select Windows Application from the Templates and click OK. You are now presented with an empty form.

We can now drag in controls in our form. But we will not drag controls in our program. Rather we will only change the title of the form.

To do so, right click on the form and select Properties. A Window named Properties pops up from the right. This will be a very useful window all the way long. Just change the Text field to �hello world�.

When we open the code part, we see the following:

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

namespace Hello_world

public class myform : System.Windows.Forms.Form

private System.ComponentModel.Container components = null;

public myform ( )

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.AutoScaleBaseSize = new System.Drawing.Size ( 5, 13 ) ;
this.ClientSize = new System.Drawing.Size ( 160, 85 ) ;
this.Name = "myform" ;
this.Text = "Hello World" ;//change the form title



static void Main ( )

Application.Run ( new myform ( ) ) ;




We have removed the comments for clarity.

The form class is derived form the System.Windows.Forms.Form class. In the constructor of this class a function called InitializeComponents( ) is called. Whatever changes we make in the Properties Window are reflected in form of code in this function. This code is written by the Windows Form Designer and is hence defined in a separate region.

If we add controls, they are also initialized in this function with corresponding changed properties. So in our form only the text and name have been changed.

In Main( ) the Run( ) method from the Application class is called. To this method an instance of the form has been passed. The Application class provides static methods and properties to manage an application, such as methods to start and stop an application, to process Windows messages, and properties to get information about an application. The Run( ) method begins running a standard application message loop on the current thread.

When we press Ctrl+F5 to compile and run the program We get the following output.

No comments: