VB6 versus WinForms


Many of the feature changes you most need to know about aren't visual; instead, they are the things that happen in the code that you write or that is generated for you as you design and program your application. However, there are new features of the Designer as well. Table A.1 summarizes the major changes.

Table A.1. VB6 versus WinForms/.NET

Feature

VB6

WinForms/.NET

Object orientation

Yes, but no implementation inhertitance

Yes

Inheritance

Interface inheritance only

Interface, implementation, and visual inheritance

Custom controls

ActiveX Control project

Deriving from UserControl

Custom control hosting

Had to program for multiple hosts

The CLR is the only host

Multiple-language support

No

Yes

Multiple-platform support

No

Yes (.NET Compact Framework, etc.)

Global application control

The App object

The Application object

Advanced features

Accessing the Win32 API

Many built into the .NET Framework, interop with Win32/COM

Application settings

.INI files, the Registry

.config files, the Registry

IDE dependence

Fully dependent on IDE

Windows applications can be written in Notepad

Generated code

Separation of code and settings in .frm files

Everything is code

Starting your application

The default form

Sub Main()

Adding controls dynamically

Control arrays

Fully supported, delegates

Input validation

The "Causes Validation" property

The error provider

Controls

Positioning

Left, Top, Height, and Width

Location, Size, Anchor, and Dock

Menus

The Menu Editor

The MainMenu and ContextMenu controls

Dialogs

Microsoft Common Dialog controls DLL

.NET Framework dialogs (OpenFileDialog, etc.)

Data grids

Microsoft DataGrid control

.NET Framework DataGrid control

Advanced controls

External ActiveX control libraries

Extended WinForms control set

The Differences

Object Orientation

Visual Basic (especially versions 5.0 and 6.0) was a powerful object-oriented development tool. However, the model was vague when it came to the visual components of an application. This was especially true of forms themselves ; it was never clear whether they were classes or objects. Sometimes, they were both at once.

This is not true in Visual Basic .NET and WinForms. WinForms is a fully object-oriented approach to building visual applications for Windows. It has a class library from which you build objects that present your application (mostly in the System.Windows.Forms namespace). The model is clear and consistent.

Inheritance

Visual Basic 6.0 offered only interface inheritance , which was necessitated by its association with COM. Interface inheritance offered Visual Basic programmers a way to implement object polymorphism , one of the three pillars of object-oriented programming. By implementing an interface, a class was signing a contract and promising to implement the methods contained therein. However, the class was fully responsible for that implementation; the interface provided only the method definitions. This ability was often the subject of heated debates: Some thought that it was a confusing addition to a straightforward language, whereas others thought that Microsoft didn't go far enough.

Visual Basic .NET still offers interface inheritance (via the Implements keyword) but also allows for implementation inheritance (via the Inherits keyword). Implementation inheritance allows programmers to derive a class (now the derived class or subclass) from another class (the base class). The subclass inherits not only the method definitions of the base class but also the method implementations along with the properties and data fields. Derived classes can access members of the base class through the MyBase keyword.

When you program in WinForms, this difference in inheritance will become immediately apparent. Any new form you create will derive from System.Windows.Forms.Form by default. Form, in turn , derives from another class, System.Windows.Forms.ContainerControl, and so on all the way back to System.Object, which sits at the root of all inheritance chains in .NET.

This opens the door to what many call visual inheritance. You can create a new class, derived from Form, that specifies a generic layout (perhaps an OK and a Cancel button in the lower-right corner). When you derive other classes from this new class, they inherit the visual styles and controls but you can add more specific features. This makes it trivial to templatize your application; changes to the new generic base form automatically cascade to the derived classes at the next build.

Custom Controls

Creating new visual controls used to involve creating a new project based on the ActiveX Control Project templates. You would have to compile the project into its own .DLL and reference it from any other projects you wished to use it for. In WinForms, on the other hand, creating a custom control is as easy as creating a class derived from System.Windows.Forms.UserControl. This class can exist inside your application project and can be used from the Toolbox or in code. See Chapter 8, Controls.

Custom Control Hosting

The ActiveX Control Project was very useful, but when creating a control, you had to be aware of and constantly code against its surroundings. The whole idea of an ActiveX control was that it could be hosted in a variety of contexts: a Visual Basic 6.0 project, a Word document, an HTML page, and so on. Programming to ensure seamless support for all these different hosts could be problematic at best.

With classes derived from UserControl in WinForms, you only have to worry about a single host: the Common Language Runtime. Because all .NET applications (or COM applications interoperating with .NET) need to leverage the CLR, it serves as the common basis for all the code.

Multiple-Language Support

Quite simply, there was none in earlier versions of Visual Basic. To use the graphical design tools, you had to write your code in Visual Basic. In contrast, WinForms is a .NET Framework library and therefore is available to any and all languages that target the Common Language Runtime: Visual Basic .NET, C#, Managed C++, J#, and so on.

Multiple-Platform Support

Visual Basic was used to create Windows applications for the Windows operating systems. Microsoft Windows was the target platform. With WinForms, the CLR is the target platform. WinForms applications should run wherever a viable CLR is running. For now, this is largely the Microsoft Windows family of operating systems, but the advent of the .NET Compact Framework for mobile devices ”as well as open source, non-Windows-hosted CLR projects such as Mono ”means that WinForms applications will in the future, be able to run on a variety of physical devices.

Global Application Control

To interact with the global application properties in a Visual Basic 6 application, you used the App object. Mainly, this was for interrogating the application about its descriptive properties: name , copyright notice, version number, and so on. You could also control application-wide logging via App. The System.Windows.Forms.Application object offers a series of shared members that provide some of the same features (property interrogation ) but provide three important new features (see Chapter 11, Applications and Settings):

  • Message filtering. You can set up application-wide Windows message filters, trapping things such as keystrokes, mouse movements, and other system notifications. You add classes that implement the IMessageFilter interface via the Application.AddMessageFilter, and remove them using Application.RemoveMessageFilter. Message trapping used to be handled through tortuous implementation of Win32 API calls.

  • Thread support. You have direct interaction with the current thread via the ExitThread() method and the OnThreadException event.

  • Application and user data storage and retrieval. CommonAppDataPath and CommonAppDataUsers provide the file path and Registry key for data storage common to all users of the application. LocalUserAppDataPath returns the file path for data storage of a local, nonroaming user of the application, and UserAppDataPath and UserAppDataRegistry provide those values for the current user of the application.

Advanced Features

You can still interact directly with the Win32 API using a feature of .NET called interop (exposed in the System.Runtime.InteropServices namespace), but you can leverage other parts of the .NET Framework to use many techniques that used to require such access. Some major areas are as follows :

  • Threading, via System.Threading (Visual Basic .NET applications can fully participate in multithreaded coding, which is a mixed blessing) See Chapter 14, Multi-Threaded User Interface

  • Run-time application and system diagnostics, via System.Diagnostics (allowing you to monitor things such as the event log, performance counters, and the current stack)

  • Socket programming, via System.Net.Sockets

  • Security services, such as cryptography, code access security, and system security principles, via System.Security

Application Settings

Local configuration settings for applications were stored in either .INI files or the Registry. .INI files were plain text files containing a series of sections, each with a series of name/value pairs. These settings were read by the application using a reader that parsed the .INI file. In WinForms applications, local settings are stored in XML files. The main configuration file is usually named App.config. You can also use the Registry and access it via the Microsoft.Win32.Registry namespace. See Chapter 1, Hello, Windows Forms.

IDE Independence

As you designed your application in Visual Basic 6.0, the metadata about your forms was stored in a proprietary format in .frm files. In theory you could create these files by hand, but you were very closely tied to the Visual Basic IDE for creating your application. In contrast, WinForms applications are written entirely in the programming language of your application, in this case Visual Basic. All properties and settings are directly accessible via the object hierarchy in WinForms and the .NET Framework as a whole. Therefore, you are no longer tied to a single IDE for developing WinForms applications. In fact, you are not tied to an IDE at all. You can create WinForms applications using only a text editor (if you don't mind a lot of typing).

Generated Code

Because the WinForms framework is completely accessible in standard code, anything generated by Visual Studio .NET (VS.NET) for you will be accessible in the code editing window. Older versions of Visual Basic hid a lot of generated information in the non-code portions of the .frm file. Now, VS.NET still hides it, but in a collapsed region in the code itself. Regions are simply a block of code that VS.NET can collapse down to a header and expand upon demand. Currently, the region is called "Windows Forms Designer generated code" and is collapsed by default whenever you open a form for editing.

Starting Your Application

The Project Properties dialog box has the same choices for starting your application as older versions. It has a drop-down list containing all forms in the application, plus Sub Main(). In older versions, Sub Main() had to live in a global .bas file, but now it can be a shared member of any class in the application (but there can be only one). If you choose one of the forms as the startup object, VS.NET actually creates a Shared Sub Main() on that form but does not create it in source code; rather, it is injected into the IL at build time.

Adding Controls Dynamically (No Control Arrays)

The days of implementing control arrays are over. Adding controls to a form in WinForms is easy. To add a new label, you might use the following code:

 
 Dim newlabel As Label = New Label() newlabel.Text = "This is a new label" newlabel.Top = 100 newlabel.Left = 100 Me.Controls.Add(newlabel) 

If you want to wire code to the new control's events, you must have existing methods that match the signature of the event. Then use the AddHandler function to add a delegate to the event's delegate list. For example:

 
 Private Sub Form_Load (ByVal sender As Object, ByVal e As EventArgs)      AddHandler newlabel.Click, AddressOf Me.labelClick End Sub Private Sub labelClick(sender As Object, e As EventArgs)   Dim clickedLabel As Label = CType(sender, Label)   MsgBox(clickedLabel.Text) End Sub 
Input Validation

Both Visual Basic .NET as well as all previous versions allow for a property to be set on many controls called Causes Validation. In both versions, this property enables events on those controls that fire when the control loses focus. In older versions, you had to create all your validation code ”and, more to the point, user notification code ”by hand. Programmers often created custom elapses to handle validation events.

WinForms provides the ErrorProvider component. You still create event handlers for the validation events of your controls. Instead of creating your own user notification code, however, you use the ErrorProvider's SetError method. It takes two parameters: the control that is being validated , and the message to display to the user. The ErrorProvider component then handles the notification through a blinking alert tag and tooltip window that displays the warning message. See Chapter 3, Dialogs, for more information.

Control Positioning

WinForms provides much better positioning attributes for controls than earlier versions of Visual Basic. Before, you were limited strictly to the Left, Top, Width, and Height properties. If you wanted to have your forms react well when users resized them, you had to trap the form's various resize and redraw events and manually move or resize your controls. WinForms introduces two new properties for control layout:

  • Anchor, which allows you to specify which edges of the form the control should be absolutely related to. If you mark a control as anchored Left and Top (the default), the space between the control and the left and top edges will remain constant (the control will not move). Anchoring it to the right and bottom, however, will move the control along with those edges if the user resizes the form.

  • Docking, which allows you to specify any single edge to dock to. The control is placed flush against the chosen edge of the form and expands to fill it entirely. At run time, the control dynamically expands and contracts with the form. Docking binds three edges absolutely: the edge flush against the chosen form edge plus the two adjacent edges, which are now flush to their edges as well. For example, docking to the left causes the control to be flush against the left side and filling the whole vertical space. Only the right edge, in this case, is floating and can be controlled either by the user or in code.

These two properties, coupled with new controls such as the status bar and splitter controls, make it much easier to create forms that react reasonably to resizing.

Menus

The venerable Menu Editor from Visual Basic 6.0 and earlier was a code-generating wizard that was fairly straightforward but not particularly usable. Its text-based representation and kludgy layout controls were bad enough, but the methodology for creating context menus (hidden menus in the main menu) was backward.

WinForms provides two new components: MainMenu and ContextMenu. Most developers who are exposed to them for the first time are immediately wowed by their editors: You edit in place on the form in a very intuitive manner, creating new menus and submenus on-the-fly . The components provide other powerful features, too. For example, ContextMenu is a first-class component. This means that you can create context menus independent of a main menu and assign them to controls simply by setting the control's ContextMenu property.

Dialogs

No longer do you have to make reference to the external .DLL Microsoft Common Dialogs in order to present your users with a file or color picker dialog. WinForms ships with the following standard dialogs:

  • OpenFileDialog

  • SaveFileDialog

  • FontDialog

  • ColorDialog

  • PrintDialog

  • PrintPreviewDialog

  • PageSetupDialog

If none of these matches your need exactly, you can create your own class that derives from the one that comes closest and add the missing functionality yourself. See Chapter 3, Dialogs.

Data Grids

The DataGrid control that ships with WinForms is much more powerful than the old Microsoft DataGrid control from Visual Basic 6.0. (For details, see Chapter 13: Data Binding and Data Grids.) Binding data is much easier and, thanks to the new ADO.NET library (System.Data), the binding is more efficient. Look-and-feel control has also been greatly improved, allowing you to design apps that don't look exactly like Excel 2.0. See Chapter 13, Data Binding and Data Grids.

Advanced Controls

In addition to the standard controls from earlier versions, WinForms ships with the following standard controls and components. In earlier versions, these controls required an external library, either Microsoft's or that of a third party. (Everything that ships with the Microsoft Windows Common Controls libraries is included with WinForms and is not listed here.)

  • LinkLabel. This is like a label but is rendered like an HTML hyperlink, with standard hyperlink semantics (a visited style, hover style, and so on).

  • GroupBox. This is the new name for a Frame.

  • Panel. This is like a GroupBox, but with no visible style of its own. It serves as a container for other controls so that they can be grouped and controlled as a unit.

  • CheckedListBox. This is like a list box, but each item has a checkbox associated with it.

  • Splitter. This control can be used in conjunction with the Docking properties of adjacent controls to automatically provide a split window style, allowing users to drag the splitter and automatically resize the other controls.

  • DomainUpDown. This shows a single text box as the display. It has an Items collection that makes up the domain of available values. The up and down arrows allow the user to scroll through the values in the domain.

  • RichTextBox. This is a multiline text box that displays rich text format (rtf) strings.

  • HelpProvider. This control allows you to easily add context-sensitive help to your application.

  • ToolTip. This provides a standard mechanism for controlling tooltip content and display styles.

  • NotifyIcon. If you want to create an application that runs in the background but interacts with the user via the Windows system tray (as in Instant Messenger), the NotifyIcon lets you assign the icon and use ContextMenu controls to create the pop-up menus the user will interact with.

  • PrintPreviewControl. This allows you to embed print preview functionality in your own forms without relying strictly on PrintPreviewDialog.

  • FileSystemWatcher. This component can be configured to watch files or directories on the file system and notify your application if those files or directories change.

  • EventLog. This reads or writes to the Windows 2000 (or later) event logs.

  • DirectoryEntry. This allows interaction with the Active Directory hierarchy. Using DirectoryEntry, you can read from or make updates to most Active Directory properties.

  • DirectorySearcher. This allows you to make queries against an Active Directory. Both DirectoryEntry and DirectorySearcher use the System.DirectoryServices namespace.

  • MessageQueue. This allows you to read, write to, and monitor an MSMQ server. It uses the System.Messaging namespace.

  • PerformanceCounter. This provides interaction with the NT performance counters. It can be used to measure things such as disk access, memory load, network traffic, and so on. It uses the System.Diagnostics namespace.

  • Process. This allows you to reach out and influence other processes running on the computer. Given the appropriate security credentials, you can start, stop, or interrogate other processes. It uses the System.Diagnostics namespace.

  • ServiceController. This allows you to start, stop, and interrogate existing Windows services on the computer. ServiceController requires appropriate security credentials. It uses System.Diagnostics namespace.



Windows Forms Programming in Visual Basic .NET
Windows Forms Programming in Visual Basic .NET
ISBN: 0321125193
EAN: 2147483647
Year: 2003
Pages: 139

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