Reusing the .NET Framework Class Library with Inheritance

   


Many of the classes in the .NET Framework class library have been designed to be base classes from which we are meant to derive new classes in our code. The System.Windows.Forms.Form (from now on simply referred to as Form) class is a core class for writing Windows GUI applications in .NET. Anybody who wants to write Windows GUI applications must derive classes from this base class.

Listing 16.7 demonstrates how easy it is to draw a window similar to that shown in the sample output after the listing by deriving a class from the Form class. Even though the displayed window looks a bit empty, it nevertheless has all the capabilities that we have come to expect from a standard window. For example, you can resize it by dragging its borders and it can be minimized, maximized, closed and dragged around on the screen; an impressive amount of functionality in return for a program taking only 15 lines of code. Furthermore, it forms the basis for any window that could contain buttons, text fields, special graphics, and so on.

Note

graphics/common.gif

The Form class resides in a dll called System.Windows.Forms.dll. At this time of writing, the compiler automatically references this library, so there is no need to explicitly reference this library when you compile the code in Listing 16.7.


Listing 16.7 MyFirstGUI.cs
01: using System.Windows.Forms; 02: 03: public class frmMain : Form 04: { 05:     public frmMain() 06:     { 07:         this.Text = "My First Form"; 08:     } 09: 10:     public static void Main() 11:     { 12:         frmMain myFirstForm = new frmMain(); 13:         Application.Run(myFirstForm); 14:     } 15: } 

graphics/16infig03.gif

The Form class is a highly complex class with many functions and data members that enable it to create and support a fully functioning window. By deriving the frmMain from the Form class as in line 3, frmMain inherits all these capabilities. This allows us to, for example, write a constructor (lines 5 8) that assigns the text "My First Form" to one of frmMain's inherited properties called Text, which controls the title on the title bar as confirmed by the appearing window.

Line 12 creates a new instance of frmMain called myFirstForm, which is then passed as an argument to the Run method. Run is a static method contained in the Application class of the System.Windows.Forms namespace. Passing myFirstForm to Run displays it onscreen and enables it to react to events, such as mouse clicks on its maximize, minimize, and close buttons.


   


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net