Master C# Logo banner
Welcome to - Master C#, the easy way... - by Saurabh Nandu


Introduction to WinForms Part - I

Add Comment

Download File .NET SDK Version (7kb) Beta2

The .NET Platform provides you with a rich set of libraries to build GUI client applications. The concept of building rapid GUI applications has been borrowed from Visual Basic Forms and its called WinForms (Windows Forms) on the .NET Platform. The WinForm API supports RAD (Rapid Application Development) and relies extensively on properties to enable you to tailor the WinForm to your needs. This part of programming is also called as Visual Programming and since we shall use C# as our programming language you can even call it Visual C# programming.

Windows Forms
Microsoft has supplied its default libraries under the System.Windows.Forms namespace in beta2 (It was System.WinForms namespace in beta1). The assembly being System.dll and  System.Windows.Forms.dll
This namespace has a class called Form, which all our Win Forms should extend. The Form class creates the basic form container which will host our controls like Textboxes, List Boxes etc. 

Also note that there are basically two types of applications on the Windows Platform namely, Console Applications and GUI/Windows Applications. Console Applications run within the MS-DOS window, while Windows Applications have their own GUI. 
When we build WinForm's we usually build Windows Applications i.e. Applications which have their own GUI and do not need a Ms-Dos window. 
To produce Windows Applications, the C# CSC compiler has a '/t:WinExe' (/target:WinExe) option. Always remember to use this switch when compiling your final WinForm application.
You might have many times seen WinForm applications (mostly the samples which install with the .NET SDK) with a Ms-Dos windows behind them and wondering, Why does the Ms-Dos window behind GUI applications appear??
Well the answer to this question has already been answered, if you don't use the '/t:WinExe' compiler options then the compiler produces a normal Console Application which has a Ms-Dos window. 
Another question you might have is, Why haven't the WinForm samples in the .NET SDK been compiled with the '/t:WinExe' option?
This is because while debugging, its easier to redirect the error output to the console screen, but in the final version of your applications you should always compile a WinForm into a Windows Application.

First WinForm
Let's kick some code! Fire up any editor (like notepad), copy the code given below and save the file as "filename.cs". Once the file is saved, start Ms-Dos Command and navigate to the directory where you have saved the file and fire the compiler command. If your code is proper you should have a filename.exe generated in the same folder. Run this file to view your WinForm

Example 1: Form1.cs

csc /t:WinExe /:System.dll Form1.cs

using System ;
//Import the WinForms Namespace
using System.Windows.Forms ;

//Class Form1 extends class Form from the
//System.Windows.Forms namespace
public class Form1 : Form
  //Main Method
  public static void Main()
    //Run the Application
    Application.Run(new Form1());

The above code is all that you need to create your first WinForm!! On close examination of the above code you will find that I have first added a 'using System.Windows.Forms' directive to import the WinForm Namespace (Incase you want to learn more about the using keyword and namespaces click here). Next our Form1 class is declared, which extends/inherits the Form class. In the Main method you will find one different statement. As I have discussed earlier while creating WinForms we are actually creating Windows Applications, in order to run such applications we have to use the static 'Run' method from the 'Application' class which also resides in the System.Windows.Forms namespace. The Application class is a sealed class (so you cannot inherit it) which takes care of running and exiting windows applications. It is also helpful to process Windows messages. The 'Run' method takes one parameter, the instance of the Application to run. 
On running the above code you should see a WinForm like Figure1 given below. The above code creates a WinForm with the default icon and three buttons to minimize, maximize and close the application respectively. Please note that unlike AWT/Swing applications in Java you don't need to handle the default minimize, maximize and close events the .NET Runtime does that for you!! But if you want then you write your own Event Handlers, that's called flexibility!! :)    

Figure 1: Form1.exe - Simple WinForm

Setting some WinForm Properties

Example 2: Form2.cs

csc /t:WinExe /:System.dll Form2.cs
using System ;
using System.Windows.Forms ;
using System.Drawing ;

public class Form2 :Form
  public static void Main()
    Application.Run(new Form2());
  public Form2()
    this.Location = new System.Drawing.Point (200, 100);
    this.Cursor = System.Windows.Forms.Cursors.Hand;
    this.Text = "Form2";
    this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
    this.AutoScaleBaseSize = new System.Drawing.Size (6, 16);
    this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
    this.ForeColor = System.Drawing.SystemColors.Desktop;
    this.Font = new System.Drawing.Font ("Times New Roman", 10);
    this.BackColor = System.Drawing.Color.Orange;
    this.ClientSize = new System.Drawing.Size (440, 170);
    //This is Windows 2000 specific property only !!
    this.Opacity = 0.80;

The above code is also same as the previous example only this time we have set a few properties in our Form2 class. Remember that these properties have been inherited by our Form2 class from the System.Windows.Forms.Form class.

On peculiar thing that you might notice is that I am accessing all the properties with the "this" keyword, for those of you who are not conversant with the "this" keyword, just think of "this" as a way of referring to the current instance of a object.  
To take a analogy, in English I would describe myself (my properties as) "My name is Saurabh", "My age is 21", "My email address is" and so on... But you will notice that the word "My" refers to me (Saurabh). Same way in programming when we use the word "this" we refer to the current instance of an object. So in the above code when I say "this.Font" or "this.Text" I mean, I am setting the properties on the current/running instance of the class Form2.   

Getting back to our code, I have also imported one more namespace "System.Drawing", this namespace contains various classes which help us drawing objects as well as it provides various class to handle Color and Size.

Let's see the function each of the property that I have set, see the Reference Documentation of a complete listing of properties.

Property Description
Location The initial location of the WinForm. The WinForm will always be displayed at this location when you run the Application. Set this property wisely, since many times you might place the form totally out of the desktop space of a person with lower (640x400) resolution! 
Cursor The cursor state when the cursor is over the WinForm.
Text The title of the WinForm, which appears next to the Icon.
StartPosition The Start Position of the Form to be drawn. This is similar to the "Location" Property, the difference being that in the Location Property you specify the exact location, while the "StartPosition" property sets Relative positions like "CenterScreen", "Manual", "WindowsDefaultLocation", "WindowsDefaultBounds" and "CenterParent" .
AutoScaleBaseSize The base minimum size by which your WinForm will resize when the user Resizes the WinForm.
FormBorderStyle The border style for your WinForm. Alternatively you can set "FixedSingle", "FixedDialog", "Sizable", "FixedToolWindow" and "SizableToolWindow" styles.
ForeColor The foreground color for the components that will be placed on the WinForm.
Font The font to be used by the components that will be placed on the WinForm. Use this property wisely, since if the font you specified does not exist on the clients system the application will terminate!! Better stick to standard windows fonts or include the font in your distribution.
BackColor The Background Color of the WinForm.
ClientSize The size of the WinForm.
Opacity This sets the transparency of the WinForm. This feature only works on Windows 2000. Try this out! (See Figure 2)


Figure 2: Form2.exe - See the Transparency !!

Adding a Component to the WinForm

Example 3: Form3.cs

csc /t:WinExe /:System.dll Form3.cs
using System;
using System.Windows.Forms;
using System.Drawing;
public class Form3 :Form
  //Declare a Label
  private Label label1 ;
  public static void Main()
    Application.Run(new Form3());
  public Form3()
    //Label initialization and setup
    this.label1 = new System.Windows.Forms.Label ();
    label1.Location = new System.Drawing.Point (24, 16);
    label1.Text = "Hello World";
    label1.Size = new System.Drawing.Size (144, 24);
    label1.TabIndex = 0;
    label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;

    this.Text = "Hello World";
    this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
    this.AutoScaleBaseSize = new System.Drawing.Size (8, 16);
    this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
    this.ForeColor = System.Drawing.SystemColors.Desktop;
    this.Font = new System.Drawing.Font("Verdana",10,System.Drawing.FontStyle.Bold);
    this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
    this.BackColor = System.Drawing.Color.Orange;
    this.ClientSize = new System.Drawing.Size (190, 170);

    //Add the label to the Form
    this.Controls.Add (this.label1);

The above code shows how to add a Label component to your WinForm. Once a form is instantiated it acts as a empty control. If you want to add any component to the form, first initialize the component (like I have initialized the Label component above) and then use the "Controls.Add()" method to add the control to the Form.  You will also notice that even the Label component uses properties to set its various attributes, this is true of all WinForm components. 

Java programmers should note that there are no such thing as LayoutManagers in C#. All the components are aligned to a fixed coordinate system which is relative to the Top Left of the Form control. This enables you to have fine grain control over the exact placement of your controls, but it comes with a small hitch! The hitch is that its very difficult for any programmer to imagine the exact position where the component should be placed during design time. 
Hence it becomes of prime importance to use visual tools/IDE's which let you position your components in WYSIWYG kind of layout. Thus if you want to program in Visual C# you need to use IDE's like Visual Studio.NET etc, unless of course you have a terrific sense of imagination!!  
In the .NET SDK beta1 Microsoft had provided a very good tool called "WinDes" which was inferior version of VS.NET but its was very good for those who could not get VS.NET. 
In .NET SDK beta2, Microsoft has removed this tool for reasons know to them :(, so until there is some other Visual IDE available you will have to get Visual Studio.NET to continue your expeditions in WinForms.

Figure 3: Form3.exe - WinForm with a Label component.

I will end this session here and give you time to get your VS.NET beta2 (working) (I heard it crashes a lot!) while I to try to get my copy (my pockets are empty -:( )!! 
Meanwhile you can surely have some fun trying the different properties of the Form class. Refer the Reference Documentation if you need to know more WinForm properties.


Add Comment