Sei sulla pagina 1di 13

Using Visual Basic 6

-2What's New with Visual Basic 6


Getting a Quick Overview of VB6
If you're new to Visual Basic, the title of this chapter might be a little confusing. Clearly if you are a novice to the language, everything about VB is new. Even so, you shouldn't avoid this chapter. There's something in it for you, particularly in the sections focusing on the new ActiveX controls. For those of you who have done some work in other versions of Visual Basic, you'll find this chapter very relevant.

What's Omitted Keep in mind that some new features in VB6 have been omitted from this discussion. These features require more than an introductory knowledge to fully understand them. Many of these features that weren't discussed, however, are covered in later chapters, whereas others are described in the documentation that comes with the product.

Saying that Visual Basic 6 has some interesting new features is nothing short of an understatement. Visual Basic 6 has so many amazing new features that overstatement is next to impossible because so much is new in so many areas. New controls allow your applications to incorporate the look, feel, and function of Office 97 applications and Internet Explorer. No more do you have to have at least one instance of a control on your form to create controls on-the-fly. With VB6, you add controls to your project dynamically with only code, and you can make custom ActiveX controls leaner and meaner than ever. You can even write server-side applications that use Dynamic HTML embedded with Internet Information Server DLLs. This chapter gives some new features a bit more attention than others. Some new improvements involve working with larger-scale data access programs that might involve hundreds--if not thousands--of users on a corporate network or on the Internet. These types of Visual Basic

applications, known as enterprise applications, are usually written with the Enterprise Edition of VB. These new enterprise features are referenced here but fall outside the scope of this book.

Working with the Windows common controls Most controls discussed in this chapter are not intrinsic (standard) ActiveX controls. Therefore, they must be added to your project from the Components dialog (choose Components from the Project menu). When you open the Components dialog, select Microsoft Windows Common Controls, Microsoft Windows Common Controls-2, and Microsoft Windows Common Controls3 from the list.

Getting More Power from Enhanced Controls


Before we look at the completely new additions to VB6, let's look at some enhancements to the features from the previous version.

The Validate Event and the CausesValidation Property


The first enhancement that affects just about all intrinsic ActiveX controls is the addition of the Validate event and the CausesValidation property. Before VB6, if you had to check to see if a word was typed properly in a TextBox, you most likely would program the TextBox's LostFocus event handler to see if, indeed, the user entered correct data. If they hadn't, you could invoke the control's SetFocus method in which validation was occurring to keep the user from proceeding. Sometimes the logic of this programming could cause your users problems. If they never entered the right data, they would be locked into that one control--they couldn't even click a Help button. The new Validate event procedure and the CausesValidation property address this issue. Listing 2.1 shows how to use the Validate event procedure to check a TextBox's data. If users don't type the word Cherries in the first TextBox, they can't proceed to the second TextBox. However, because the value CausesValidation property of the CommandButton is set to False, users can click it to help determine the right word to enter.

Using the CausesValidation property Notice the Cancel parameter on Line 1. Visual Basic provides this parameter within the control's Validate event procedure. If you set the value of Cancel to True (Line 7), the program's focus won't be allowed to leave the control except to go to other controls that have their CausesValidation property set to False.

LISTING 2.1 02LIST01.TXT--Allowing Some Controls Event Handling Activity During Data Validation
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 Private Sub Text1_Validate(Cancel As Boolean) `Make it so that if the user does not `enter the word, "Cherries" in the TextBox `the cursor will be returned this TextBox If Text1.Text <> "Cherries" Then MsgBox "You cannot go on!" Cancel = True End If End Sub Private Sub Command1_Click() Dim strMsg As String Dim strQuote As String strQuote = """" `Make an instructional message strMsg = "You must type the word," & strQuote strMsg = strMsg & "Cherries" & strQuote & " " strMsg = strMsg & "in the first TextBox." MsgBox strMsg, vbInformation, "Instructions" `The reason that you can click on this `CommandButton even though the Cancel parameter `of the Validate event handler is set to True `is because the value of CauseValidation `property of this CommandButton is set to false. End Sub

Commenting code The apostrophe (`) before a line of code denotes a commented line. That line of code isn't run by Visual Basic.

The Validate event procedure allows you to check for correct data while still allowing you to access other controls during the validation process.

Adding Excitement with the New Graphical Enhancements


Visual Basic, as always, allows you to use graphics to make your programs come alive, and Microsoft has enhanced the graphical capabilities of many controls. First, the ImageList control now supports .gif files. This enhancement is substantial because just about every control that uses graphics has an ImageList control associated with it. The ListView and TabStrip controls have been enhanced to allow you to use pictures and icons for decoration and description.. The background picture can be centered, tiled, or placed at any corner. You can add check boxes to ListItems child objects within the control by setting the ListView's CheckBoxes property to True. Also, you can make the scrollbars of the ListView appear in the new flat style by setting the FlatScrollBars property to True.

You now can have a background graphic in the ListView control client area. The new TabStrip control, which now allows you to place graphics in each tab. The control also has a new property, HotTracking, that you can assign at design time. If you set the value of HotTracking to True, the tab highlights when you pass the mouse pointer over it. As mentioned earlier, as with all the new controls, the TabStrip control has a Validate event procedure. The TabStrip control has been enhanced to allow for icons on each tab. The Slider control has a new property, Text. When you set a string to the value of the Text property, that string appears within a ToolTip window. The position of the ToolTip window is determined by the Slider control's new TextPosition property . The Slider control now has a Text property that shows you a ToolTip window. Many enhancements have been made to the ToolBar control. You can now add drop-down menus to the toolbar by using a ButtonMenu. The Style property supports a transparent setting (tbrTransparent) that allows you to have the buttons on your toolbar appear and behave like the buttons on the Internet Explorer toolbar. The ToolBar control is enhanced to provide ButtonsMenus and hotspots. The control's property page allows you to configure a ToolBar at a very detailed level.

Working with the New Controls


Visual Basic 6 ships with many new ActiveX controls. Some of these controls apply to standalone desktop programs; others pertain to enterprise-wide data access development projects. In the following sections, you'll see the new controls that relate to your desktop development efforts.

Selecting Dates with the MonthView and DateTimePicker Controls


VB6 has two controls that provide you with a new way to view and select dates: MonthView and DateTimePicker. What's interesting about these controls is that they let you view and select dates within the context of a calendar. The MonthView control presents a full calendar that you can traverse from day to day or month to month. The DateTimePicker control is similar to the MonthView except that its calendar drops down when the user clicks the control's down arrow. All the new Windows common controls are embedded in the OCXs MSCOMCTRL.OCX, MSCOMCT2.OCX, and COMCT332.OCX.

Making Movable Toolbars with the CoolBar


The new CoolBar control is similar to the Coolbars you've been using in Office 97 and Internet Explorer. A CoolBar is a toolbar that you can move on a form, and the CoolBar control is a container for other ActiveX controls. Thus, you can offer your users more flexibility and utility

by embedding other controls within the CoolBar. At runtime you can move the Bands around the Coolbar's client area any way you want.

CoolBar bands A band is a bar within a CoolBar. A CoolBar can have many bands that can be moved about in the CoolBar client area.

Using Graphics with an ImageCombo


Working with ImageLists An ImageList is a "windowless" control that you use to store different types of graphics: bitmaps, gifs, icons, and so on. You associate an ImageList with a control by assigning the ImageList in question to a control's ImageList property. For example, to assign an ImageList named ImageList1 to an ImageCombo, the code is ImageList1.ImageList = ImageList1.

The ImageCombo control, new with Visual Basic 6, allows you to embed graphics within a ComboBox. To accomplish this, Visual Basic introduces a new object, the ComboItem, which encapsulates all layout and data properties that are needed to work with an ImageCombo. A ComboItem has a Text property for string display of a line within the ImageCombo and an Image property that can define the graphic to show on a line within the ImageCombo. As with most of the new graphical ActiveX controls, the ImageCombo has an ImageList from which it references images and pictures. Use the code in Listing 2.2 to add a ComboItem that has a graphic to an ImageCombo. This code is from the cmdAddCbo_Click() event procedure of the CommandButton cmdAddCbo, which is part of the code from the project WhatsNew.vbp. You can download the code from the Web side dedicated to this book. LISTING 2.2 02LIST02.TXT--Creating ComboItems and Adding Them to an ImageCombo
01 02 03 04 05 06 07 08 09 Static i% `A counting integer Static imgi% `A index for a graphic `within an ImageList Dim ci As ComboItem `Object variable for a `ComboItem `Get a reference to ComboItem object using `a ComboItems Add method. Set ci = ImageCombo1.ComboItems.Add

10 11 12 13 14 15 16 17 18 19 20 21 22 23

`Assign some data a line of text `ci.Text = "My Caption " & CStr(i%) `Add a graphic by referencing an index in the `associated ImageList ci.Image = imgi% + 1 `Make sure that you haven't exceeded the number `of images in the ImageList If imgi% = ImageList1.ListImages.Count - 1 Then imgi% = 0 Else imgi% = imgi% + 1 End If `Increment the string counter i% = i% + 1

Code for the ComboItem If you're beginning programmer, the code shown in Listing 2.2 is probably a little beyond your needs right now. This code is provided to show those with some VB background how to work with the newer features of the ComboItem object.

Figure 2.6 shows you the result of clicking the cmdAddCbo button. Notice that the ImageCombo contains a graphic and a string.

The FlatScrollBar Control


Visual Basic 6 provides a new variation of the familiar scrollbar control: the FlatScrollBar. The FlatScrollBar is fundamentally the same as the ScrollBar, except that the FlatScrollBar has three Appearance styles: a standard style, a three-dimensional (beveled) style, and a two-dimensional style that becomes beveled when the mouse pointer hovers over it.

Working with the New Language Features


In addition to enhanced and new ActiveX controls, VB6 also provides new features within the Visual Basic language itself. Again, if you have no previous experience with Visual Basic, the following sections might seem a bit baffling. You still might want to read through it anyway, however; these new features will make your programming efforts easier regardless of degree of prior experience.

File System Objects


In older versions of Visual Basic, if you wanted to get file system information or perform file system tasks, such as writing to a file or changing a directory, you had a number of techniques available, most of which were quite laborious. In Visual Basic 6, all these chores have been contained with a new object, FileSystemObject, which is part of the Visual Basic Scripting Library. Thus, when you learn to use this object within VB6, you can easily transfer your

knowledge to scripting within Internet Explorer or Internet Information Server to do system-level programming.

Internet Information Server Internet Information Server (IIS) is a complex program, the function of which is to deliver information and files over the Internet. An Internet server is a physical computer, and IIS is software that runs on an Internet server. As you read in this book, you'll learn that you can use Visual Basic to write programs that are extensions of IIS, called IIS Applications. An application that runs on an Internet server is called a server-side application.

The FileSystemObject is quite complex. It's made of a number of objects and methods that encapsulate the file system functions, which you use to work with drives and files on a local machine or over the network. Table 2.1 describes the new FileSystemObject objects.

Microsoft Scripting RunTime component If you plan to program with the FileSystemObject, make sure that you include a reference in your project to the Microsoft Scripting RunTime ActiveX component. You include a reference to the MS Scripting RunTime through the References dialog (choose References from the Project menu). Then select the Microsoft Scripting RunTime in the References list.

TABLE 2.1 FileSystemObject Objects Object Drive File Folder Description Provides properties and methods for describing and working with local and network drives Provides properties and methods for working with files Provides properties and methods for working with folders

FileSystemObject Provides properties and methods for defining and working with collections of drives, folders, and files TextStream Provides properties and methods that allow you work with text files

If you want an introduction to the FileSystemObject, the project prjFileSystem.vbp is a small program that shows you how to use the various FileSystemObject features to find out how many drives are on your computer. Also, when you select a found drive, the program reports back the amount of unused disk space on a drive. You can find the project prjFileSystem.vbp on the Web site dedicated to this book.

The project prjFileSystem gives you an introduction about how to use the FileSystemObject.

New String Functions


Visual Basic 6 provides a number of new functions for working with strings (see Table 2.2). TABLE 2.2 The New String Functions Function (Return Type) Filter (string array) FormatCurrency (string) FormatDateTime (string) InStrRev (string) Join (string) MonthName (string) Replace (string) Round (string) Split (string array) StrReverse (string) WeekdayByName (string) Name Description Allows you to filter a string for various substrings Allows you to format a string to currency Allows you to format a string to a time or date

FormatPercent (string) Allows you to format a string as a percent Returns the position of one string within another string; unlike InStr, InStrRev starts at the end of the string being searched Takes a string array and combines its elements into one string Returns the name of a month when you have the number of the month (for example, 1 returns January) Replaces substrings within a string Returns a rounded number as specified Splits a string into an array of strings Reverses the order of a string--for example, "cat" becomes "tac" Returns the day of the week

As you can see in Table 2.2, some new string functions return string arrays. The capability of a function to return an array is also a new feature in VB6. Each new function listed in Table 2.2 could warrant a section of a chapter dedicated solely to it. Clearly, such description is beyond the scope of this chapter, but if you need more details for how to use a specific string function, read the documentation that comes with your edition of VB6 or Chapter 12, "Working with Strings and Typecasting."

True Dynamic Control Creation


On-the-fly versus runtime

The phrase on-the-fly is used when you are creating something while a program is running. Another term for the state when a program is running is runtime.

For those of you familiar with VB, you might know that in prior versions of VB you created controls on-the-fly by using control arrays. One drawback to creating controls with a control array was that at least one control had to be present on a form for you to create others dynamically. This is no longer true in VB6; you can create a control at runtime purely from code by using the Add method of the Controls collection. Listing 2.3 shows you the code that you must use to create a CommandButton purely from code, without having to drag a CommandButton from the ToolBox first. LISTING 2.3 02LIST03.TXT--The New Add Method for the Controls Collection
01 02 03 04 05 06 07 08 09 10 11 12 12 14 15 16 17 18 19 20 Option Explicit `WithEvents is a way tell the program to `respect all the events that are associated `a CommandButton such as the click event. Private WithEvents cmdMyButton As CommandButton Private Sub Form_Load() Set cmdButton = Controls.Add("VB.CommandButton", _ "Button") With mdButton .Visible = True .Width = 3000 .Caption = "A real surprise" .Top = 1000 .Left = 1000 End With End Sub Sub cmdButton _Click() cmdButton.Caption = "At last, real OOP! End Sub

If you want to see this code in action, go to the project prjDynCtrl.vbp on the Web site dedicated to this book.

Learning About VB and the Internet


Working with DHTML Dynamic Hypertext Markup Language is an extension of HTML (Hypertext Markup Language), the language of the Internet. All Web browsers, regardless of manufacturer, use HMTL to decode information passed through the Internet that's presented to end users. DHTML takes HTML one step further by permitting a greater degree of programmability to take place. Thus,

with DHTML you can send code via the Internet that allows end users to move things around the computer monitor with a mouse, to hide things, or even to delete items.

Visual Basic has been positioned very nicely for Internet development. You can use VBScript to write applications that run on your desktop computer with Internet Explorer. Also, you can use VBScript on the server side to work with Internet Explorer. Visual Basic 6 has sharpened the focus on Internet development; it extends your ability to write server-side applications for Microsoft's Internet Information Server by introducing a project type named IIS Applications. Also, Visual Basic extends and simplifies DHTML (Dynamic Hypertext Markup Language, the language used by all Web browsers) by introducing a project type named DHTML Applications. For more about programming with VB, VBScript, and DHTML, read Chapter 28, "Creating VB Programs for the Internet." An IIS application is a Visual Basic program that resides server side as an extension of Internet Application Server. An IIS application is called by a client computer via the Internet. Although the Visual Basic IIS Application sends data back to the calling client through HTML, the actual calculation on the server-side computer is done by using compiled Visual Basic code. This enhancement is significant; before this, IIS Applications were written in C++ or, if you wanted to program IIS, you had to do it with VBScript under Active Server Pages (ASP).

VB's integrated development environment IDE stands for integrated development environment. The Visual Basic IDE is your programming workbench, where you write and debug code as well as manage your applications. You'll learn more about the Visual Basic IDE in Chapter 3, "Working in the Visual Basic 6 Programming Environment."

A DHTML application is a project that presents a Visual Basic Designer, a tool that automates the writing of VB code. The DHTML Application Designer allows you to write DHTML code within the Visual Basic IDE. You can find the actual DHTML on the IIS Web server in the form of an ActiveX DLL. This is significant because DHTML is somewhat different than VB code. Thus, you're leveraging the inner workings of IIS and VB to actually translate VB into DHTML at runtime. One problem with programming for the Internet is that the programming dynamic is stateless by nature. Interaction is analogous to a telephone call. Every time you contact a server on the Internet, it's as though you're making a telephone call to a stranger who has no prior knowledge of the information passed in any previous call. Therefore, working with a body of data that must be transmitted from session to session is difficult. Visual Basic uses a new feature within Internet Explorer, the Global Property Bag, to allow you to share information from session to session.

Microsoft has extended the Setup Wizard into a set of new tools to make publishing your application to and deploying it from a Web server easier. These tools--the Web Publishing Wizard and the Package and Deployment Wizard--come as part of your purchase when you buy your edition of Visual Basic 6. You'll take a close look at the Web Publishing Wizard and the Package and Deployment Wizard in Chapter 20, "Deploying Your Visual Basic Applications."

Finding Out About the New Data Capabilities


Visual Basic 6 supports ActiveX Data Objects (ADO). In prior versions of VB, data access was handled under the umbrella of Data Access Objects (DAO) and Remote Data Objects (RDO). ADO has combined and superseded these technologies. ADO is easier to use and has a broader scope of implementation. You can use ADO to connect to a database on a local desktop or to a remote database server. Also, ADO allows you to access more types of data--e-mail, for example. The current ADO technology is contained within the new ADO Data control. The ADO Data control might look the same as the familiar Data control of prior versions, but when you look at the Property Page of the control , you see a significant difference. The ADO control allows you to connect to a desktop database file or an ODBC server on a network, or you can create a new connection to another database. The ADO data control combines the functionality of DAO and RDO, as well as allows you to access non-traditional data types such as e-mail or files within the file system. In addition to ADO, Visual Basic 6 also comes with a new set of tools and technologies that make data access easier. The Data Environment Designer allows you to view and manipulate data in various databases. Because data environments are objects in their own right, you can use them as you would a Data control. You can even bind other controls, such as a TextBox or Label, to a Data control. Some new data controls allow you take advantage of the enhancements built into the ADO Data control. The DataGrid allows you to view your data in a row and column format. The DataList and DataCombo are similar to the DBList and DBCombo in earlier editions of VB; you can use them to get a pick list of data from an ADO control in a ListBox or ComboBox configuration. You also can use the more advanced FlexGrid and hierarchical FlexGrid controls to get a clear, visual view of complex data. Visual Basic also provides a new Data Setup Wizard to make deploying your larger-scale database applications easier. Visual Basic 6 enhances its reporting capabilities with the Data Report Designer , which lets you create, preview, and print reports in Visual Basic as you would in Access. (If you've worked in Access 97, you'll find the Data Report Designer familiar.) You set report controls from the new Data Reports Toolbox (VB also has some new IDE features) onto the Data Report form. Then you invoke the Data Report's PrintReport() method. Granted, as you go along, you'll find things to be more complex. You can get more details on Data Environments and Data Reports in the chapters in Part V of this book, "Database Programming with Visual Basic 6."

The Data Report Designer brings the ease of Access 97 reporting to Visual Basic.

New Object Programming Additions


Visual Basic 6 has made creating classes and ActiveX controls a much broader activity. You can now save your custom-made class's data from session to session in a Property Bag. You can also create two new types of data-aware custom classes, Data Sources and Data Consumers. These types of data classes behave very much as the ADO Data objects, except they allow you to have more flexibility to suit your custom needs. With regard to custom ActiveX controls, you now can make lightweight ActiveX controls in VB6. These types of controls are "windowless" and thus require fewer system resources than full-fledged ActiveX controls. To determine if an ActiveX control is indeed windowless, Visual Basic provides a new property, HasDC.

Using add-ins An add-in is a Visual Basic tool that VB programmers make for other VB programmers. An addin is written in VB and can run only within the Visual Basic IDE. The Application Wizard is an add-in, as is the Data Forms Wizard.

Probably the most helpful additions to Visual Basic 6 are all the new wizards that come bundled with it. Table 2.3 briefly describes each new wizard and add-in. TABLE 2.3 Visual Basic 6 Wizards and Add-Ins Wizard/Add-In All Editions Package and Deployment Wizard Application Wizard Description Helps you prepare and deploy your application for desktop or network use. Helps you set up a framework for your application. It automatically adds menus, toolbars, resource files, intrinsic ActiveX controls, and data controls. Helps you organize the various wizards that you can access within your IDE.

Wizard Manager Professional and Enterprise Editions Data Object Wizard

Helps you create data objects bound to data controls and custom ActiveX controls.

Class Builder Utility ToolBar Wizard Data Form Wizard Add-In Designer

Helps you visually build custom classes. Helps you visually create custom toolbars for your forms. Helps you create forms with controls that reference data in a database. Helps you create custom VB add-ins.

Property Page Wizard Helps you create property dialogs for the ActiveX controls you make in VB. T-SQL Debugger API Viewer ActiveX Control Interface Wizard Helps you debug code that you write for Microsoft's SQL Server Database. Helps you work with declares (functions), constants, and types from the Windows API. Helps you make ActiveX controls.

HAKAN KIRIK

Potrebbero piacerti anche