Platinum Edition Using Visual Basic 5

Previous chapterNext chapterContents


- 27 -
Creating ActiveX Documents

You will learn the differences and similarities between ActiveX documents and standard Visual Basic applications.
You will see how to use the Visual Basic design environment to create ActiveX documents.
You will see how a UserDocument object compares with a standard form and how it differs. You also will see how to add properties to a UserDocument.
You will see how to use the Hyperlink object to move back and forth between the multiple documents of a project.
You will see that, although you have to use a second program such as Internet Explorer to test your documents, all of Visual Basic's debugging tools are available to you.

You probably are aware that there are a lot of things happening with the Internet these days. In particular, the World Wide Web has gained enormous popularity. It seems that everywhere you turn, everyone has a Web site--from car manufacturers to charitable organizations to the guy next door. Internet stuff is everywhere. And although it used to be acceptable to just have a static Web page, more and more people and organizations are providing dynamic content on their pages. These interactive Web pages do a lot more than just display fixed information. It is commonplace to see Web pages that act like applications, and a variety of tools are available to let you create such pages.

When you first take a look at creating interactive content, it can appear very daunting--I know it did for me. More often than not, the concern I hear is not "Can I do this?" but "What's the best way to do this?" When you try to think of ways to program for the Web, dozens of terms may come to mind: PERL, CGI, Active Server Pages, VBScript, and Java, to name a few. The ActiveX documents discussed in this chapter are not necessarily the best choice for all occasions, but they do make Internet programming very accessible to VB programmers.

Understanding ActiveX Documents

Since ActiveX documents are perfect for use on the World Wide Web, this chapter will begin with a quick refresher course. You probably have become familiar enough with Web pages to know that they are basically just document files. Web files are very similar to Word documents except they are written in a special format: HTML (which stands for Hypertext Markup Language). Just as Word is the viewer for .doc files, a Web browser (such as Netscape or Internet Explorer) is used to view HTML files. HTML files on the Internet have an address, or URL (Universal Resource Locator), that is used to locate a specific document.

That's how the Web began, just a bunch of linked documents. But a static document cannot produce the level of interactivity we see today. Two things about the Web have made this possible:

The Hypertext Transfer Protocol, or HTTP, is the means by which your browser and the Web server communicate. The browser simply requests an URL, and then displays the returned HTML stream.

Notice that I use the word "requests"--this is an important concept. Requesting a file is very different from opening one on your hard drive; hence the need to have a protocol. Think of this process as being similar to you asking a friend to send you a document via e-mail. Unlike opening a document on your hard drive, your friend could edit the document before sending it, or send you a completely different document. In a similar manner, logic can be placed on the Web server to modify the returned document based on any number of things.

On the browser side, the returned HTML stream has evolved quite a bit since the Web's first days. In addition to formatted text and graphics, Web pages can include script code and Java applets. These advances were made possible by the increasing complexity of the Internet browser, which has evolved to support all of these embedded objects. ActiveX documents, discussed in this chapter, take browser enhancements to a new level.

What Is an ActiveX Document?

Put in simplest terms, an ActiveX document is an application that runs inside a container, such as Internet Explorer, instead of running as a stand-alone program. An example of such an application is shown in Figure 27.1.

FIG. 27.1
A simple ActiveX document running in Internet Explorer.

The "document" portion of the name comes from the analogy to word processing documents or spreadsheets. These files contain data, but must be accessed by a program in order to be viewed or edited. For example, you can create a document in Word and store it in a file. If you pass the file along to another user, that user can't do anything with it unless they have a copy of Word. An ActiveX document works much the same way. You can create an ActiveX document and store it in a file. If you pass the file to someone else, they must have a program capable of supporting ActiveX documents before they can use the file.

Fortunately, there are many containers that support ActiveX documents, including Internet Explorer, Microsoft Office 97 binders, and the Visual Basic IDE. Your users will run your program inside one of these container applications.

What Are the Advantages of ActiveX Documents?

The primary reason to use ActiveX documents in Visual Basic is to create Internet-enabled applications. Creating ActiveX documents provides a number of advantages over creating Internet applications by other means. Some of these advantages include:

So, Visual Basic makes it easy to create an ActiveX document, but why would you want to create one in the first place? Why not just create a standard application? The answer, in a word, is "Internet." ActiveX frees you of the complications involved with the older means of distributing an application. If your program is a standard EXE, then you must send install disk to all of the users. ActiveX documents, on the other hand, can be set up on a Web server so that they are downloaded automatically when a user opens the Web page. Codes embedded in the Web page tell Internet Explorer to download a cabinet (CAB) file containing your application and all necessary components. This Web-based approach makes it simpler to maintain your code and to keep everyone running the same version.

Creating Your First ActiveX Document

Creating an ActiveX document is very similar to creating standard applications in Visual Basic. In this chapter, we re-create the loan payment calculator example from Chapter 3, "Creating Your First Program," but this time as an ActiveX document. To create a document, we will follow this basic sequence of events:

1. Start a new ActiveX document project.

2. Create the user interface of the application.

3. Write the code to perform the application's tasks.

4. Test and debug the application.

5.
Use the Setup Wizard to create an Internet download setup.

Obviously, there are a number of details involved in each of these steps, but you can see that the process is something with which you are familiar. To walk through the process of creating an ActiveX document, you will create a mortgage calculator like the one you created in Chapter 3. Using this same application will illustrate the similarities between creating an ActiveX document and a standard Visual Basic program.


NOTE: The preceding steps refer to creating an application. Since an ActiveX document is an interactive application, as opposed to a static file, such as word processing documents, the term application will often be used to refer to an ActiveX document.

Starting an ActiveX Document Project

The first step toward creating an ActiveX document is to start your project. You do this by selecting the New Project item from the File menu. This opens the New Project dialog box (see Figure 27.2). From this dialog box, select the option to create an ActiveX Document EXE by double-clicking the icon. This starts the new project and displays a blank UserDocument form on the screen, as shown in Figure 27.3.

FIG. 27.2
Select the project type to create from the New Project dialog box.

FIG. 27.3
A UserDocument object looks very much like a form.


NOTE: If the UserDocument is not displayed automatically, double-click the UserDocument object in the Project window to display it.

Notice that the UserDocument looks a lot like a form without a border. As a matter of fact, it is exactly like the UserControl object that you will use to create ActiveX controls. You will create the user interface for the ActiveX document here, just like with a form. (For more information about creating ActiveX controls, see Chapter 24, "Creating ActiveX Controls.")

After you have created the project, change the properties of the project and the UserDocument to descriptive names, as listed in Table 27.1. To access the properties of the project, choose projectname Properties from the Project menu. The properties of the UserDocument are accessible from the Properties window (View, Properties Window). After setting the properties, save the files of the project by clicking the Save button on the toolbar. You then specify names for each of the new files.

Table 27.1 Project and UserDocument Properties

Property Setting
Project Type ActiveX EXE
Project Name ActXCalc
Project Description ActiveX Document Loan Calculator
UserDocument Name CalcDoc


Document File Names
The source code of ActiveX documents is saved in a text file, much the same way a form is saved. The description of the UserDocument object and any controls is stored along with the code of the document in a file with the extension .dob. This is similar to the .frm file of a form. If there are any graphical components of the interface, these are stored in a .dox file, similar to the .frx file for forms. When you compile your ActiveX document, you create either an .exe or .dll file, along with a .vbd file. The .vbd file is the one accessed by Internet Explorer. This .vbd file is the "document" part of the file, similar to a .doc file from Microsoft Word.

Creating the Interface of the Document

The interface of your ActiveX document is created by drawing controls on the UserDocument object, just as you would draw them on the form of a standard program. You can use almost any Visual Basic control in the creation of your document. The only exception to this statement is that you cannot use the OLE Container control as part of an ActiveX document. Another restriction is that an ActiveX document cannot contain embedded objects, such as Word or Excel documents.


CAUTION: If you use custom controls in your document, you need to check licensing and royalty requirements before distributing the controls.

To create the interface of the sample application, you need to add four Label controls, four TextBox controls, and one CommandButton to the UserDocument.

The Label controls should have the following settings for the Name and Caption properties:

Name Caption
lblPrincipal Principal:
lblTerm Term (Years):
lblInterest Interest Rate (%):
lblPayment Monthly Payment:

All four text boxes should have their Text properties deleted so that the text boxes appear empty when the document is first shown. The text boxes should be named txtInterest, txtPayment, txtPrincipal, and txtTerm.

The command button of the document should have the Name property set to cmdCalculate and the Caption property set to Calculate Payment.

When you have completed adding the controls to the document, your UserDocument should look like the one in Figure 27.4.

FIG. 27.4
The Document calculator looks similar to the LoanCalc program created earlier.

Adding Code to the Document

After you create the interface of the document by using Visual Basic controls, you are ready to write the code that makes the document perform a task. As with the forms in a standard program, you will write code for events of the controls in the document. All code work is done in the Code window. You can access the Code window by double-clicking a control or by clicking the View Code button in the Project window. For the sample application, you need to enter the code from Listing 27.1 in the Click event of the command button.

Listing 27.1 CALCDOC.DOB--Placing Code in the Click Event to Run the Calculation

Private Sub cmdCalculate_Click()
    
    Dim m_Principal As Single, m_Interest As Single
    Dim m_Payment As Single, m_Term As Integer
    Dim m_fctr As Single
    
    m_Principal = txtPrincipal.Text
    m_Interest = txtInterest.Text / 1200
    m_Term = txtTerm.Text
    m_fctr = (1 + m_Interest) ^ (m_Term * 12)
    m_Payment = m_Interest * m_fctr * m_Principal / (m_fctr - 1)
    txtPayment.Text = Format(m_Payment, "Fixed")

Testing Your ActiveX Document

After entering the code and saving your document, you are ready to test the code. Testing an ActiveX document is a little different than testing a standard program because the document must run inside another application. To test your code, follow these steps:

1. Run your document by pressing F5 or clicking the Start button on the toolbar. (Note that Visual Basic will not display the user interface of your program.)

2. Minimize Visual Basic and start Internet Explorer.

3. From IE's File menu, choose the Open item. This will present an Open dialog box in which you can enter the name of the file to be opened by IE.

4. Specify the path and name of your ActiveX document and the name. The name will be the value of the Name property of the UserDocument object, followed by a .vbd extension. If you are running your document within VB, the file is located in the same folder as Visual Basic. For a typical installation, this is C:\Program Files\DevStudio\VB.

5. Click the OK button in the Open dialog box to load your document. The CalcDoc document is shown running in Internet Explorer in Figure 27.5.

FIG. 27.5
Internet Explorer can host an ActiveX document.


NOTE: If you click the Browse button of the Open dialog box to find the file, remember to change the Files of Type selection from HTML files to All Files.

If your code doesn't perform like it should, you can use all of Visual Basic's debugging tools to track down and eliminate errors. (Debugging is discussed in detail in Chapter 8, "Programming Basics.") You can set breakpoints in your code, set "watches" to observe the values of variables, and step through the code line by line to locate an error. Figure 27.6 shows a typical debugging session.

See "Making Your Program Bug-Free," Chapter 8


CAUTION: Terminating your program without closing Internet Explorer may cause errors in IE. Therefore, you should close and restart IE each time you run your document.

Compiling Your Document

After you have finished testing and debugging your document, you are ready to compile the document for distribution. To start the compilation process, select the Make item from the File menu of Visual Basic. This opens the Make dialog box, in which you specify the name and location of the EXE or DLL file. The name of the .vbd file is based on the Name property of the UserDocument object. This file is placed in the same folder that you specified for the EXE file.

FIG. 27.6
Debugging tools make it easy to find and correct errors.

After compilation, your document can be used in any of the programs that handle ActiveX documents. As you learned previously, Internet Explorer is one such program. The Office 97 Binder is another. To access an ActiveX document with the Binder, start the Binder and then select the Add from File item in the Section menu. This opens a dialog box that enables you to specify the file to be loaded. You specify the name and location of your .vbd file and then click the OK button to load the document. Figure 27.7 shows the CalcDoc document running inside the Office 97 binder.

FIG. 27.7
The Office 97 Binder provides another means with which to run your ActiveX documents.

If you want to put your ActiveX document on the Internet, you first need to run the Setup Wizard with the Internet Download Setup option. The Wizard will create a CAB file that contains the required components, as well as sample HTML that shows you how to include your document on a Web page. It also creates a SUPPORT directory with the components in the CAB file, should you need to modify anything.

See "Distributing ActiveX Controls by Using Setup Wizard," Chapter 25

Exploring the UserDocument Object

Just as a form is the main part of a standard program, the UserDocument object is the key part of an ActiveX document. The UserDocument provides the container for all the controls that make up the user interface of the document. Like a form, you can place controls on the UserDocument or you can use graphics methods and the Print method to display other information directly on the document. This provides great flexibility in the design of your documents and the manner in which you present information to the user.

Understanding the Key Events of a UserDocument

Although the UserDocument is similar to a form in many respects, there are also some key differences. For example, there are several key properties, methods, and events that are supported by a UserDocument but are not supported by a form, and vice versa.

The main events of a form that are not supported by the UserDocument object are the Activate, Deactivate, Load, and Unload events. The UserDocument, on the other hand, supports the following events that are not supported by a form:

Creating and Storing Properties for a UserDocument

Despite the similarities between the UserDocument and a form, there are some ways in which the UserDocument is much more similar to a UserControl than a form. All three objects--the form, the UserControl, and the UserDocument--enable you to create properties and methods to extend their capabilities. However, only the UserControl and the UserDocument have the capability to use the PropertyBag object. The PropertyBag object, along with some special events, is used to store values of public properties so that settings are preserved between sessions.

Since the process for creating and saving properties was discussed in detail in the coverage of ActiveX controls, the details won't be repeated here (see Chapters 24, "Creating ActiveX Controls" and 26, "Creating a User-Drawn Control"). However, a quick recap will help you remember the steps involved. To create and store properties for the UserDocument, you need to do the following:

1. Create a property by using the Property Let and Property Get procedures. You can create the shell of the property by using the Add Procedure dialog box, accessible from the Tools menu of Visual Basic.

2. To indicate that the value of a property has changed, place the PropertyChanged statement in the Property Let procedure of each property whose value you want to store.

3. To store the values of the property, use the WriteProperty method of the PropertyBag object to output the values of the changed properties. The code for this is placed in the WriteProperties event of the UserDocument.

4. To retrieve the values of the property, use the ReadProperty method of the PropertyBag object to output the values of the changed properties. The code for this is placed in the ReadProperties event of the UserDocument.

See "Creating the Properties of the Button," Chapter 26

The result of the code for handling these tasks in a sample document is shown in Figure 27.8.

FIG. 27.8
Use the ReadProperty and WriteProperty methods to retrieve and store public properties of the UserDocument.

Working with the Methods of the UserDocument

In addition to the different events that are supported by the UserDocument, there are also two key methods that the UserDocument supports but a form does not: AsyncRead and CancelAsyncRead. The AsyncRead method enables the document to request that its container read in data from a file or URL. As the name implies, the read is performed asynchronously. The AsyncRead method requires that you specify the file (or information) to be read and the type of information that is being read. There are three supported data types, as summarized in Table 27.2. The following line of code shows how the method can be used:

AsyncRead "C:\Vb\Default.Htm", vbAsyncTypeFile

As you can imagine, reading a file asynchronously comes in very handy when working with the Internet. For example, you might write a data viewer application that retrieves information from a server.

Table 27.2 Types of Data Supported by the AsyncRead Method

Constant Description
vbAsyncTypeFile The data is contained in a file created by Visual Basic.
vbAsyncTypeByteArray The data is a byte array containing retrieved data.
vbAsyncTypePicture The data is stored in a picture object.

The CancelAsyncRead method is used to terminate an asynchronous read prior to its completion.

Using the Hyperlink Object in Your Document

One object of extreme importance in ActiveX documents is the Hyperlink object. This object has no properties and only three methods. However, the Hyperlink object is what enables an ActiveX document to call another ActiveX document, or to navigate to a Web site. The three methods of the Hyperlink object are the following:


NOTE: A container such as Internet Explorer, which supports hyperlinking, will execute on its own the jump specified in a NavigateTo method. A container such as Office 97 Binder, which does not support hyperlinking, will start a hyperlink-capable program to process the jump.

Using the ActiveX Document Migration Wizard

So far, you have learned how to create an ActiveX document from scratch. But, if you are like me, you have a lot of time and effort invested in creating standard Visual Basic applications. Is there any way that you can capitalize on the work you have already done, short of using cut and paste to bring in pieces of a program?

Fortunately, the answer is yes. Visual Basic provides a tool called the ActiveX Document Migration Wizard that can help you convert forms from an existing application to UserDocument objects for an ActiveX document. The key word here is "Help." The Wizard does not create a complete ActiveX document directly from your standard application. Instead, the Wizard does the following:

Although the ActiveX Document Migration Wizard can do a lot of the work of converting a document for you, there are some things that it cannot handle. Therefore, you have to do some coding work before you can compile and distribute your document.

First, you need to remove unsupported events, such as Load and Unload. Although the Wizard will comment out the Load and Unload statements, it will not do anything with the event pro-cedures code. If you use these events to initialize the properties of a form or its controls, you may want to move some of the code from the Load event to the Initialize event of the UserDocument. Likewise, you may want to move some of the code from the Unload event to the Terminate event of the UserDocument.

You also need to make sure that you do not reference any non-existent objects. For example, if you migrate a form to a UserDocument, any references to the form by name (such as "Form1") would be invalid.

Running the ActiveX Document Migration Wizard

To run the ActiveX Document Migration Wizard, you need to make sure that it is available in Visual Basic. You make the Wizard available by selecting it from the Add-In Manager dialog box, which is accessible by choosing the Add-In Manager item from the Add-Ins menu. After you have added the Wizard to your desktop, you can run it by choosing the ActiveX Document Migration Wizard item from the Add-Ins menu.

To begin converting the forms of a project into ActiveX documents, you first must open the project's forms that you want to convert. The Wizard will work correctly only from within the project. Next, start the ActiveX Document Migration Wizard. This presents the introductory screen, which explains a little of what the Wizard will and will not do for you. Click the Next button on the Wizard to proceed to the second screen--where the work begins.

The second screen of the Wizard, shown in Figure 27.9, enables you to select the forms from the current project that you want to convert to ActiveX documents. All the forms of the current project are shown in the forms list. You can select any form by clicking the check box next to the form name. Multiple selections are allowed. After you have made your selections, click the Next button to proceed to the next step of the process.

FIG. 27.9
Select your forms from the list in the Wizard.

The Options page of the ActiveX Document Migration Wizard, shown in Figure 27.10, lets you control how the Wizard will process the forms you have selected. The three options enable you to do the following:

FIG. 27.10
Select the options that are appropriate to your needs.

After making your choices, click the Next button to proceed. The final page of the Wizard asks if you would like to see a summary report after the Wizard's part in the conversion has been completed. After making your selection, click the Finish button to begin the conversion. The summary report, shown in Figure 27.11, describes which additional activities you need to perform to complete the conversion process.

FIG. 27.11
The ActiveX Document Migration Wizard uses a summary report to guide you through the rest of the conversion process.

Looking at the Results of the Wizard's Work

When the ActiveX Document Migration Wizard has finished its work, it places the newly created UserDocument objects in the same project as the original forms. The document source files are stored in the same folder as the original form files and are given similar names, with the appropriate extension. For example, a form stored in the file frmTest1.frm would create a UserDocument stored in the file docTest1.dob. As previously stated, the controls of the form are copied to the UserDocument and their relative positions are preserved. Figure 27.12 shows both the original form and the resulting UserDocument.

Also, as stated previously, most of the code from your original form is copied over to the UserDocument. Invalid code is commented out and identified by the ActiveX Document Migration Wizard. (This assumes that you chose to comment out invalid code on the Options page of the Wizard.) Figure 27.13 shows an example of this process.

FIG. 27.12
The UserDocument and the original form have the same user interface.

FIG. 27.13
Invalid code is identified by the [AXDW] mark in a comment statement.

Creating a More Complex Document

Obviously, there is only so much room available on a UserDocument object. Therefore, you are limited in the amount of information that can be displayed in a single document. In this regard, a single document is like an application with a single form. However, you can create additional documents as part of your project and then navigate between the various documents. You can also include standard forms in the applications that you create with ActiveX documents. This section takes a look at what is involved in using multiple documents and forms in your ActiveX document-based application.

Programming Additional Documents

To use additional documents in your ActiveX application, you need to create the additional documents and then provide a mechanism for moving back and forth between the documents. This is a little different than moving between forms in a standard program because the UserDocument object does not support the Load and Unload statements, or the Show and Hide methods that are available to forms.

The first step necessary to add another document to your project is to add another UserDocument object to the project. You do this by choosing the Add User Document item from the Project menu. This places a second (or third, fourth, and so on) document in your project, under the UserDocuments folder. As with the first document you created, you need to specify a name for the document.

The next step required is to draw the interface of the additional document and add the code that enables it to do its tasks. This process is the same as the one you used to create the original document.

Now for the tricky part! Since you cannot use the Show method to display a document (as you can with forms), how do you get back and forth between the various documents in your application? The answer is to use the NavigateTo method of the HyperLink object. The NavigateTo method instructs a container application to go to a particular file or URL and load the page. If the file is an ActiveX document, it gets processed just like your original page.

To move from your first document to your second, you need to run the NavigateTo method as shown in the following line of code:

HyperLink.NavigateTo App.Path & "\docnav2.vbd"

The App.Path property specifies the path to the current document. By using this as the basis for locating the second document, the document can be loaded without incident, provided that the documents are stored in the same directory. Figures 27.14 and 27.15 show the two pages of a sample document loaded in Internet Explorer. To get from the second document back to the first, you use the NavigateTo method again. For both documents, the method is used in code that responds to an event. The event is typically the Click event of a command button.

FIG. 27.14
The first document of a multiple document application.

When you moved to the second document of the application, you may have noticed that the Back button of Internet Explorer was enabled. You can use this button to move back to the first document. However, you should provide a direct link using the NavigateTo method because the first document may not always be the previous document in the history list. Also, if the first document has scrolled out of the history list, the NavigateTo method is the only way to get to the document again.

FIG. 27.15
The second document of a multiple document application.

Using and Displaying Forms from the Document

In addition to working with more than one document, you can work with standard forms in your ActiveX document applications. To use a form in a project, you create it the same way you would create a form for a standard project--draw the interface of the form and write the code to perform tasks. To display the form from your document, use the Show method. Then, to remove the form, use the Unload statement.


NOTE: For more information about creating forms, see Chapter 4, "Working with Forms and Controls."

Although forms can be part of your application, they are not handled the same way as documents. Forms are not contained within the application that contains the ActiveX document. Forms are independent of the container, as shown in Figure 27.16.

Fig. 27.16
Forms are outside the boundaries of the document container.

From Here...

This chapter introduced you to the world of ActiveX documents. You have seen how these documents make it easy to create applications that can run inside Internet Explorer or other ActiveX-enabled container applications. You also have seen the similarity between the UserDocument object and the forms of a standard application.

This chapter also touched on some other topics related to the creation of ActiveX documents that are covered in more detail in other chapters. To learn more about these topics, see the following chapters:


Previous chapterNext chapterContents


Macmillan Computer Publishing USA

© Copyright, Macmillan Computer Publishing. All rights reserved.