Introduction to WinForms Part - I
Add Comment<div align="center"> <table border="0" width="70%" class="outline"> <tr> <td width="50%" class="outline"><b>Download File</b></td> <td width="50%" class="outline"><b>.NET SDK Version</b></td> </tr> <tr> <td width="50%" class="outline"><a href="../../file/introwinform1.zip" class="wbox">introwinform1.zip</a> (7kb)</td> <td width="50%" class="outline">Beta2</td> </tr> </table> </div> <p><span class=wboxheado>Introduction</span><br> 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 <a href="http://www.mastercsharp.com/article.aspx?ArticleID=9&&TopicID=4" class="wbox">properties</a> 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.</p> <p><span class=wboxheado>Windows Forms</span><br> Microsoft has supplied its default libraries under the <b>System.Windows.Forms</b> namespace in beta2 (It was System.WinForms namespace in beta1). The assembly being <b>System.dll</b> and <b>System.Windows.Forms.dll</b>. <br> This namespace has a class called <b>Form</b>, which all our Win Forms should <i>extend</i>. The Form class creates the basic form container which will host our controls like Textboxes, List Boxes etc. <br> <br> Also note that there are basically two types of applications on the Windows Platform namely, <b> Console Applications </b> and <b> GUI/Windows Applications</b>. Console Applications run within the MS-DOS window, while Windows Applications have their own GUI. <br> 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. <br> To produce Windows Applications, the C# CSC compiler has a '<i>/t:WinExe</i>' (/target:WinExe) option. Always remember to use this switch when compiling your final WinForm application.<br> 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, <i>Why does the Ms-Dos window behind GUI applications appear??</i><br> 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. <br> Another question you might have is, <i>Why haven't the WinForm samples in the .NET SDK been compiled with the '/t:WinExe' option?</i><br> 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.</p> <p><span class=wboxheado>First WinForm</span><br> 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</p> <p><b>Example 1:</b> Form1.cs <table border="0" width="100%" class="code"> <tr> <td width="100%"><pre><span class=cmt>/* Compile: csc /t:WinExe /:System.dll Form1.cs */</span> using System ; <span class=cmt>//Import the WinForms Namespace</span> using System.Windows.Forms ; <span class=cmt>//Class Form1 extends class Form from the //System.Windows.Forms namespace</span> public class Form1 : Form { <span class=cmt>//Main Method</span> public static void Main() { <span class=cmt>//Run the Application</span> Application.Run(new Form1()); } }</pre></td> </tr> </table> <p>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 '<i>using System.Windows.Forms</i>' directive to import the WinForm Namespace (Incase you want to learn more about the using keyword and namespaces <a href="http://www.mastercsharp.com/article.aspx?ArticleID=18&&TopicID=4" class="wbox">click here</a>). Next our <b> Form1</b> class is declared, which extends/inherits the <b> Form class</b>. In the <b> Main</b> 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 '<b>Run</b>' method from the '<b>Application</b>' 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. <br> 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!! :) <br> <br> <img border="0" src="../../img/winformaform1.gif" width="300" height="300"><br> <b>Figure 1: </b> Form1.exe - Simple WinForm</p> <p><br> <span class=wboxheado>Setting some WinForm Properties</span> <p> <b>Example 2:</b> Form2.cs <table border="0" width="100%" class="code"> <tr> <td width="100%"><pre><span class=cmt>/* Compile: csc /t:WinExe /:System.dll Form2.cs */</span> using System ; using System.Windows.Forms ; using System.Drawing ; public class Form2 :Form { public static void Main() { Application.Run(new Form2()); } <span class=cmt>//Constructor</span> 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); <span class=cmt>//This is Windows 2000 specific property only !!</span> this.Opacity = 0.80; } }</pre></td> </tr> </table><p>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.<br> <br> On peculiar thing that you might notice is that I am accessing all the properties with the "<b>this</b>" 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. <br> 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 saurabh@mastercsharp.com" 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. <br> <br> 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.</p> <p>Let's see the function each of the property that I have set, see the Reference Documentation of a complete listing of properties. <table border="0" width="100%" class="outline"> <tr> <td width="25%" class="outline"><b>Property</b></td> <td width="65%" class="outline"><b>Description</b></td> </tr> <tr> <td width="25%" class="outline">Location</td> <td width="65%" class="outline">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! </td> </tr> <tr> <td width="25%" class="outline">Cursor</td> <td width="65%" class="outline">The cursor state when the cursor is over the WinForm.</td> </tr> <tr> <td width="25%" class="outline">Text</td> <td width="65%" class="outline">The title of the WinForm, which appears next to the Icon.</td> </tr> <tr> <td width="25%" class="outline">StartPosition</td> <td width="65%" class="outline">The Start Position of the Form to be drawn. This is similar to the "<i>Location</i>" Property, the difference being that in the Location Property you specify the exact location, while the "<i>StartPosition</i>" property sets Relative positions like "CenterScreen", "Manual", "WindowsDefaultLocation", "WindowsDefaultBounds" and "CenterParent" .</td> </tr> <tr> <td width="25%" class="outline">AutoScaleBaseSize</td> <td width="65%" class="outline">The base minimum size by which your WinForm will resize when the user <i>Resizes</i> the WinForm.</td> </tr> <tr> <td width="25%" class="outline">FormBorderStyle</td> <td width="65%" class="outline">The border style for your WinForm. Alternatively you can set "FixedSingle", "FixedDialog", "Sizable", "FixedToolWindow" and "SizableToolWindow" styles.</td> </tr> <tr> <td width="25%" class="outline">ForeColor</td> <td width="65%" class="outline">The foreground color for the components that will be placed on the WinForm.</td> </tr> <tr> <td width="25%" class="outline">Font</td> <td width="65%" class="outline">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.</td> </tr> <tr> <td width="25%" class="outline">BackColor</td> <td width="65%" class="outline">The Background Color of the WinForm.</td> </tr> <tr> <td width="25%" class="outline">ClientSize</td> <td width="65%" class="outline">The size of the WinForm.</td> </tr> <tr> <td width="25%" class="outline">Opacity</td> <td width="65%" class="outline">This sets the transparency of the WinForm. This feature only works on Windows 2000. Try this out! (See Figure 2)</td> </tr> </table> <p> </p> <table border="0" class="outline"> <tr> <td width="100%"><img border="0" src="../../img/winformaform2.gif" width="471" height="228"></td> </tr> </table><b>Figure 2:</b> Form2.exe - See the Transparency !! <p><br> <span class=wboxheado>Adding a Component to the WinForm</span> <p> <b>Example 3:</b> Form3.cs <table border="0" width="100%" class="code"> <tr> <td width="100%"><pre><span class=cmt>/* Compile: csc /t:WinExe /:System.dll Form3.cs */</span> using System; using System.Windows.Forms; using System.Drawing; public class Form3 :Form { <span class=cmt>//Declare a Label</span> private Label label1 ; public static void Main() { Application.Run(new Form3()); } <span class=cmt>//Constructor</span> public Form3() { <span class=cmt>//Label initialization and setup</span> 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); <span class=cmt>//Add the label to the Form</span> this.Controls.Add (this.label1); } }</pre></td> </tr> </table><p>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 "<b>Controls.Add()</b>" 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. <br> <br> Java programmers should note that there are no such thing as LayoutManagers in C#. All the components are aligned to a <b> fixed coordinate</b> 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. <br> 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!! <br> 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. <br> 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.</p> <p><img border="0" src="../../img/winformaform3.gif" width="200" height="200"><br> <b> Figure 3:</b> Form3.exe - WinForm with a Label component.</p> <p><span class=wboxheado>Conclusion</span><br> 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 -:( )!! <br> 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.</p>