Windows GUIs: System.Windows.Forms

< BACK  NEXT >
[oR]

It can sometimes seem as if browser-based applications have taken over the world. While developers once devoted a great deal of time to getting the Windows GUI right, they now also sweat technical bullets over details of HTML and JavaScript. Browsers have become the new default interface for a whole generation of software.

Browser interfaces are very common today

But Windows GUIs still matter. The ascendancy of browsers notwithstanding, applications that directly access pixels on a screen are not going away. Recognizing this fact, the designers of the .NET Framework provided a new set of classes that allow CLR-based applications to build Windows GUIs. Contained in the System.Windows.Forms namespace, these classes are commonly referred to as Windows Forms.

Windows interfaces remain important

Building GUIs Using Windows Forms

Stripped to its essentials, an application that presents a GUI displays a form on the screen and then waits for input from the user. This input is typically processed by a message loop, which passes the input on to the appropriate place. For example, when the user clicks a button or hits a key or moves the mouse, events that are sent to the form the user is accessing are generated. The form and any code attached to it handle these events and then write output to the screen.

The typical model for a GUI is a form with code that responds to events

In Windows Forms, every form is an instance of the Form class, while the message loop that accepts and distributes events is provided by a class called Application. Using these and other classes in System.Windows.Forms, a developer can create a single-document interface (SDI) application, able to display only one document at a time, or a multiple-document interface (MDI) application, able to display more than one document simultaneously.

Windows Forms follows the traditional model

Each instance of the Form class has a large set of properties that control how that form looks on the screen. Among them are Font, which indicates what font should be used for any text displayed on the form; Size, which controls the form's initial on-screen size; and nearly a hundred more properties. Developers can set these properties to customize a form's appearance and behavior.

Forms have properties

Forms commonly contain other classes called Windows Forms controls. Each of these controls typically displays some kind of output, accepts some input from the user, or both. The System.Windows.Forms namespace provides a large set of controls, many of which will be familiar to anyone who's built or even used a GUI. The control classes available in this namespace include Button, TextBox, CheckBox, RadioButton, ListBox, ComboBox, and many more. Also provided are more complex controls such as OpenFileDialog, which encapsulates the operations that let a user open a file; SaveFileDialog, which encapsulates the operations that let a user save a file; PrintDialog, which encapsulates the operations that let a user print a document; and several others.

Forms can contain Windows Forms controls

Like a form, each control has properties that can be set to customize its appearance and behavior. Many of these come from System.Windows.Forms.Control, a class from which every control inherits. (In fact, even the Form class inherits from System.Windows.Forms.Control.) The Button control, for example, has a Location property that determines where the button will appear relative to its container, a Size property that determines how big the on-screen button will be, and a Text property that controls what text will appear in the button.

Controls have properties

Forms and controls also support events. Some examples of common events include Click, indicating that a mouse click has occurred; GotFocus, indicating that the form or control has been selected by the user; and KeyPress, indicating that a key has been pressed. In fact, all of these events and several more are defined in the base Control class from which all Windows Forms controls inherit. A control can also support unique events that have meaning only to it.

Both forms and controls can respond to events

A developer can create code to handle events received by a form or control. Called an event handler, this code determines what happens when the event occurs. Handling events relies on delegates, the type provided by the CLR for passing references to methods in a type-safe way.

Code that responds to events is called an event handler

Here's a very simple C# example that illustrates the basic mechanics of forms, controls, and event handlers. While this example works, some things are simpler than they really should be, so you shouldn't necessarily view this as paradigmatic for your own code.

public class ExampleForm : System.Windows.Forms.Form {     private System.Windows.Forms.Button myButton;     public ExampleForm()     {        Text = "An Example Form";        myButton = new System.Windows.Forms.Button();        myButton.Location = new            System.Drawing.Point(50, 50);        myButton.Size = new System.Drawing.Size(175,            50);        myButton.Text = "Click Here";        myButton.Click += new            System.EventHandler(myButton_Click);        Controls.Add(myButton);     }     private void myButton_Click(object sender,         System.EventArgs e)     {        System.Windows.Forms.MessageBox.Show(            "Button clicked");     } } class DisplayForm {     static void Main()     {        System.Windows.Forms.Application.Run(new            ExampleForm());     } } 

This example begins by declaring the class ExampleForm. Like all forms, this one inherits from System.Windows.Forms.Form. (This code contains no using statements, partly to make it shorter and partly to make clear where the various types can be found in the .NET Framework class library.) The ExampleForm class then declares a private instance of the System.Windows.Forms.Button class, one of the controls mentioned earlier, called myButton.

The next thing to appear is the constructor for the ExampleForm class. The constructor is automatically run whenever an instance of this class is created, and in this example, the constructor's job is to initialize appropriately the form and the control it contains. The first step in that initialization is to set the form's Text property. The constructor then creates an instance of the Button class and sets several of its properties. Those properties include Location, Size, and Text, all of which were described earlier. Once this is done, the constructor sets up an event handler for the Click event on myButton. This is done using EventHandler, a standard delegate provided in the System namespace. Finally, the myButton control is added to the control collection for this form, something that must be done to allow the control's output to be displayed.

Following the ExampleForm class's constructor is the method that will handle the Click event on myButton. By convention, the format of this method's name is the name of the control followed by an underscore and the name of the event: myButton_Click. This isn't required, however, and in fact any name can be used. The standard arguments to the event handler method allow learning more about the event, but they're not used in this simple ex ample. Instead, the event handler just calls the Windows Forms MessageBox method to output a simple message.

The example ends with a class containing just one method Main which itself has only one statement, a call to the Run method of the System.Windows.Forms.Application class. This method provides a message loop that accepts and processes events. Passing it an instance of a form, as in this case, causes it to make that form visible when the application runs.

The output of this program is shown in Figure 5-11. As you would expect, it consists of a single form containing a button with the text Click Here . The figure shows how things look after a user has clicked the button, causing the event handler for the Click event to run. The result is the message box that appears to the right of the form.

Figure 5-11. The simple application described in this section shows a form containing a button control; then it displays a message box when the button is clicked.
graphics/05fig11.gif

It's certainly possible to hand-code GUIs using the types in System.Windows.Forms, but only a masochist would do it.

Visual Studio.NET allows creating forms interactively

While it's useful to see a simple example to get a sense of how the mechanism works, the vast majority of Windows GUIs will be created using Visual Studio.NET or some other tool. Visual Studio.NET provides a full-featured designer that allows dragging controls onto a form, directly setting their properties, and adding code to handle events. The full implementation is then generated automatically by this tool. Creating a GUI in this way is faster, more accurate (since you can see what you're doing), and much less error-prone.

Windows Forms Controls

Windows Forms controls are a very useful way to package reusable chunks of functionality. Although the .NET Framework class library provides a large set of controls, the inventiveness of developers knows no bounds. Accordingly, the .NET Framework makes it straightforward to write custom Windows Forms controls. As already mentioned, every Windows Forms control must inherit either directly or indirectly from the class Control. It's also possible to inherit from one of the standard controls provided with the .NET Framework class library, basing a new control on existing functionality, or to combine two controls into one new one. Whatever choice the control's creator makes, a good chunk of the work is done for her. Because the new control can be built on what the .NET Framework already provides, building one is significantly easier than it was in the Windows DNA era.

Developers can create custom Windows Forms controls

Windows DNA applications can use COM-based components known as ActiveX controls. Despite being fairly complicated to create, huge numbers of these are available from third parties. Many containers capable of running ActiveX controls also exist, including Internet Explorer and the Windows shell. Given this large installed base of both ActiveX controls and containers for those controls, there must be some way for Windows Forms controls to interoperate with this world.

There is a way. To use an ActiveX control in a Windows Form environment, the ActiveX Control Importer, Aximp, can be used to create a wrapper for the control. As with other parts of the .NET Framework's support for COM interoperability, this tool reads the ActiveX control's type library and produces an assembly containing analogous metadata. To allow a Windows Forms control to be used in a container that expects only ActiveX controls, the Windows Forms control can inherit from the class UserControl. This class implements everything required to make the Windows Forms control look like an ActiveX control and thus be hostable in the many ActiveX control containers that exist today. Also, because ActiveX controls are COM-based, any Windows Forms control used in this way must have an entry in the Windows registry, just as in the COM interoperability scenarios described earlier in this chapter.

Windows Forms controls can emulate ActiveX controls

In Windows DNA, Visual Basic and C++ had completely different approaches to building GUIs. Because of this, ActiveX controls were based on COM, which allowed them to work with both languages. The predictable result was complexity. Windows Forms sweeps away the accumulation of GUI technologies that have built up on the Windows platform, replacing them with a single consistent approach. While you may lament the effort required to learn this new approach, there is certainly some appeal in finally having just one way to build Windows user interfaces.

Windows Forms provides a common mechanism for creating GUIs in any CLR-based language

< BACK  NEXT >


Understanding. NET. A Tutorial and Analysis
Understanding .NET: A Tutorial and Analysis (Independent Technology Guides)
ISBN: 0201741628
EAN: 2147483647
Year: 2002
Pages: 60

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