'; zhtm += ''; zhtm += '

' + pPage + ''; zhtm += ''; window.popUpWin.document.write(zhtm); window.popUpWin.document.close(); // Johnny Jackson 4/28/98 } //--> Using Visual Basic 6 -- Ch 29 -- Making Programming Easier with Visual Basic Add-Ins


Using Visual Basic 6

Previous chapterNext chapterContents


- 29 -
Making Programming Easier with Visual Basic Add-Ins


Working with Add-Ins

An add-in is a design-time tool that you attach to the Visual Basic IDE. Generally, an add-in simplifies, enhances, or automates some aspect of your programming activity. You can use add-ins to build classes; view API functions, structures, and constants; or help create deployment packages of your applications or custom ActiveX controls.

Attaching Add-Ins to the Add-Ins Menu

Visual Basic 6 ships with a number of add-ins, which you attach to the IDE by using the Add-In Manager.

Attach an add-in to the VB programming environment

1. Choose Add-In Manager from the Add-Ins menu.

2. In the Add-In Manager dialog, select an add-in from the list (see Figure 29.1).

3. Select one or more of the Load Behavior check boxes.

4. Click OK.

FIGURE 29.1 You use the Add-In Manager to attach an add-in to the IDE.

If you select Loaded/Unloaded as a load behavior, the add-in appears immediately in the IDE as an item in the Add-Ins menu (see Figure 29.2). If you selected Load on Startup, you need to close Visual Basic and restart it.

FIGURE 29.2 Some tools that ship with Visual Basic, such as the API Viewer, can be attached to the IDE as an add-in.

Attaching Add-Ins to the Add-Ins Toolbar

In addition to attaching add-ins to Visual Basic's Add-Ins menu, you can display an add-in toolbar to which you can insert buttons for various add-ins. This toolbar itself is an add-in, so you first must attach it to the IDE. After you insert the toolbar, you insert buttons representing different add-ins.

Display the Add-In toolbar

1. Choose Add-In Manager from the Add-Ins menu.

2. Select VB 6 Add-In Toolbar from the Available Add-Ins list.

3. Select the Loaded/Unloaded check box.

4. Click OK to insert the toolbar in the Visual Basic IDE (see Figure 29.3).

Insert add-ins in the toolbar

1. Click the Add/Remove Add-In button on the add-in toolbar to display the Add/Remove Toolbar Items dialog (see Figure 29.4).

FIGURE 29.3 The add-in toolbar is blank until you insert some add-ins except for the Add/Remove icon.

FIGURE 29.4 The add-ins that you insert in the add-in toolbar won't be displayed on the Add-Ins menu.

2. Select the add-ins that you want to add to the toolbar.

3. Click OK to close the dialog and insert the add-ins into the toolbar (see Figure 29.5).

FIGURE 29.5 The add-in toolbar is really a coolbar control.

Using Add-Ins


Third-party tools

A third-party tool is one made by one developer to support another developer. For instance, Microsoft is the maker of Visual Basic, but another company may make a control or an add-in designed to work with and add value to Visual Basic. The company that makes the tool to support VB is considered a third party, whereas you, the user of the product, are considered the first party and Microsoft is considered the second party.


As mentioned, Visual Basic ships with a number of third-party add-ins. Some of these add-ins are advanced. Most are provided to make your day-to-day programming much easier. Let's look at two: the Application Wizard and the Data Form Wizard.

Using the VB6 Application Wizard

The Application Wizard add-in allows you to quickly create a framework for your application. The Application Wizard is a great tool for creating simple applications and also for implementing front ends (menus) for your programs.

Create a Multiple Document Interface application with a File menu


The wizard creates a shell program

If you really want to do specific things with a program created with the Application Wizard, you may have to do more programming. The Application Wizard can create programs that handle information very well, but you may have to do more programming if you want to do much more. It at least provides you with basic code to start with and gives you some learning experience if you have never programmed before.


1. Click the icon on the add-in toolbar.

2. Let the profiles setting stay at (None) in the Application Wizard dialog (see Figure 29.6). Click the Next button.

FIGURE 29.6 Eventually you'll have a number of preset profiles from which you automatically create different types of applications. You can save these profiles at the end of the creation process in the Application Wizard.


Separating menu items

You use separator bars in menus for several reasons. For example, if you have several categories of icons (such as programming, applications, and databases), you could separate these items and make it easier to find what you're looking for.


3. Select the Multiple Document Interface (MDI) option button and enter a name for your application in the text box at the bottom of the dialog (see Figure 29.7). Click Next.

4. Deselect all menu items except &File in the Menus list. Deselect all submenu items except &New, &Open, &Close, and E&xit in the Sub Menus list (see Figure 29.8). Click Next.

5. Remove all toolbar buttons from the application's toolbar except for New and Open by selecting the button in the list on the right and clicking the left-arrow button (see Figure 29.9). Click Next.

FIGURE 29.7 You can choose an MDI, SDI, or Explorer interface for your application. A visual and descriptive hint appears in the upper left of the dialog.

FIGURE 29.8 Select menu items you want to include in your application and then select which submenu items to include.

6. Select No to avoid adding a resource string to the project (see Figure 29.10). Click Next.

7. Select No again to avoid adding a Web page and default URL to your project (see Figure 29.11). Click Next.

FIGURE 29.9 You add or remove the various images that you want to associate with an application's toolbar in the Customize Toolbar page of the Application Wizard. An example of the toolbar is shown at the top of the dialog.

FIGURE 29.10 You can embed a table of string directly into your executable if you decide to make a string resource file.

FIGURE 29.11 If you want, you can auto- matically make your application Web enabled.

8. Leave all the check boxes deselected on the Standard Forms page of the wizard (see Figure 29.12). Click Next.

FIGURE 29.12 You can add a splash screen, login, custom settings, and an About box form to your application.


Working with resource files

With resource files, you can distribute your application in multiple languages and increase the performance of the application. The Resource Editor add-in will store the resource file in memory until the project is saved. After it's saved, the resource file will appear in the project but under the Related Documents category.


9. Don't add any data forms to your application (see Figure 29.13). Click Next.

10. Don't save this application configuration as a profile (see Figure 29.14). Click Finish.

FIGURE 29.13 You can create or add forms that reference a database to your application.

FIGURE_29.14 You can save the application's framework configuration as a profile so that the next time you want to create this type of application, you load the profile within the wizard.

As you can see in Figure 29.15, the Application Wizard has created a project according to the settings provided. Because you chose to make an MDI project, you have an MDI form and a child form. The wizard created a module as well as named and saved the forms and project. The wizard also added an ImageList control and a CommonDialog control to the project to provide images and functionality for the menus and toolbar.

FIGURE 29.15 The Application Wizard makes a full-fledged MDI application project with little effort.

Using the VB6 Data Form Wizard


The Biblio and Northwind databases

Microsoft ships two Access data-bases with every copy of Visual Basic: Biblio.mdb and Nwind.mdb. These databases are fictitious. Biblio represent a database of books and publishers. Northwind is a database of an imaginary food company, Northwind Traders. These databases are provided so that you have formal data on which to test your data-access tools and routines. These are also great resources to learn from.


Many Visual Basic applications involve accessing and working with data on a database or some other type of data source. Therefore, having a tool that allows you to quickly make forms that map to a given database is a useful addition to your programming toolbox. The Data Form Wizard is such a tool.

The Data Form Wizard is an add-in that ships with Visual Basic 6. You attach the Data Form Wizard to the VB IDE by using the Add-In Manager to add it to the Add-Ins menu. Alternatively, you can attach the add-in toolbar to the IDE and then add the Data Wizard to the add-in toolbar. Both techniques are described earlier in the section "Working with Add-Ins."

After you attach the Data Form Wizard to the IDE, you take the following steps to create a Data Form for the Access database Biblio.mdb.

1. Invoke the Data Form Wizard by selecting it from the Add-Ins menu or by clicking the icon on the add-in toolbar. The Data Wizard - Introduction dialog appears (see Figure 29.16).

FIGURE 29.16 The Data Form Wizard allows you to load a predefined profile from a prior use.

2. Let the profile setting stay at the default, (None). Click Next.

3. Select Access from the list of the wizard's Database Type dialog (see Figure 29.17). Click Next.

FIGURE 29.17 You can choose between ODBC and Access databases.

4. Click the Browse button to browse for an Access database. Select Biblo.mdb from the dialog (see Figure 29.18) and click Open. Click Next.

5. Enter a name for the data form, keep the form layout as Single Record, and keep the binding type as ADO Data Control (see Figure 29.19). Click Next.

FIGURE 29.18 When you choose an access database, you need to provide the database filename and location.

FIGURE 29.19 You can view a thumbnail of the layout type in the upper left corner of the wizard's Form dialog.

6. Select the Titles table from the Record Source drop-down list (see Figure 29.20). Select the Subject, Title, and Year Published fields in the Available Fields list and click the button to move the fields into the Selected Fields list. Select Subject from the Column to Sort By drop-down list and then click Next. (For more information on ADO, see Chapter 30, "Database Basics and the Data Control," and Chapter 32, "Enhancing Your Programs Using the Advanced Data Controls.")

7. Click Next to accept the defaults (all available controls) on the wizard's Control Selection dialog (see Figure 29.21).

8. Leave the profile settings drop-down list set to (None) on the wizard's last dialog (see Figure 29.22). Click Finish. You may want to save the profile of this file so it will be available to you next time around.

FIGURE 29.20 You decide the precise data you want to view by selecting tables and fields from within the wizard's Record Source dialog.

FIGURE 29.21 You can use Add, Update, Delete, Refresh, and Close buttons on your data forms.

FIGURE 29.22 You can save the Data Form Wizard's settings to a custom profile as you can in the Application Wizard.

After you click Finish, the wizard creates a form that's bound to the database of your choice by the method that you've chosen. By following the preceding steps, you create a database that's connected to the Titles table of the Bibli.mdb database. The form shown in Figure 29.23 includes the Subject, Title, and Year Published fields, as well as all the buttons that you selected to be included.

Clearly, if you do much data-access work, the Data Form Wizard is a tool that saves you a significant amount of time. As you become a more developed programmer, you'll create a set of profiles within the wizard that you can use repeatedly.

FIGURE 29.23 The Data Form Wizard creates a data-bound form in seconds, as opposed to the hours you'd have to spend creating the form on your own.

Creating a Custom Add-In


Designers

A designer is a programming tool written in C++ that Visual Basic programmers use to generate code for a specific functionality. Designers present a graphical user interface to programmers. Programmers enter programming information into the designer, and the designer in turn generates the appropriate code. VB6 ships with designers for data access, add-ins, Internet components, and DHTML pages, to mention a few. In this chapter, you use the Add-In Connect Designer.


Visual Basic 6 is created in such a way as to make writing a custom add-in feasible for less experienced programmers. Although making a custom add-in was possible in prior versions of Visual Basic, it was difficult even for the more experienced programmer. Visual Basic 6 ships with an add-in project type that you can select when you start a new project. The add-in project uses the Add-In Connect Designer to automatically do many of the fundamental tasks associated with creating an add-in (see Figure 29.24). The Add-In Connect Designer is included as a module within the add-in project, as is a starting form on which you create a graphical user interface for your add-in.

Let's look at a custom add-in that every programmer needs: an automatic procedure-header generator. Good code is well commented. In the heat of programming, however, many developers forget to put in the all-important procedure header that describes what a particular procedure is about and what it does. The add-in ProcHeader is a custom add-in that allows programmers to generate the code that declares a procedure, either Sub or Function. When the procedure is declared, the add-in inserts a predefined procedure header template into the code.

First, you need to generate the framework for the add-in. Then, you code the specifics for the add-in.

FIGURE 29.24 The Add-In Connect Designer automatically generates code for your custom add-in.

Create the framework

1. Choose New Project from Visual Basic's File menu.

2. Select Addin in the New Project dialog (see Figure 29.25).

3. Select the Connect Designer in the Project window. Then click the View Form icon to display the Designer form (refer to Figure 29.24).

4. Enter the data in the Designer form as shown in Figure 29.24.

FIGURE 29.25 The Addin project automatically creates a framework on which you can make a custom add-in.

An add-in--even one made by using the designer built in to the add-in project--generates a volume of code that's beyond the breadth of an introductory chapter. Therefore, the code that you need in order to work with the following can be found at http://www.mcp.com/info. To gain the most from the following, you might want to open the code in the VB6 IDE and follow along.

How the Add-In Works

The way the custom add-in works is that you choose an option from the Add-Ins menu to display the add-in's form. You select whether the procedure is to be a Sub or Function and Private or Public in scope (see Figure 29.26). When you click OK, the add-in goes to the bottom of the code pane and adds a procedure declaration with a code header. The code header text is defined in an external text file, header.txt. Last, the add-in moves the text cursor in the code pane to the location of the newly inserted lines of code so that the code pane displays the declaration for the new procedure.

FIGURE 29.26 The Procedure with Code Header add-in allows you to declare a Sub or Function and automatically include a procedure header.

Error traps are put in to ensure that there are no errors when accessing the external text file or when writing to the code pane.

The add-in is an ActiveX DLL and compiled as such. When you compile the code, the project automatically includes the newly compiled add-in to the list of available add-ins in the Add-In Manager.

When you deploy the add-in to other programmers, you deploy it as you would any other ActiveX DLL or EXE. For more information about deploying an ActiveX DLL, see Chapter 20, "Deploying Your Visual Basic Applications."

Understanding the Visual Basic 6 IDE Object Model

Making custom add-ins is possible because Visual Basic exposes itself as a set of interrelated objects that you can manipulate. You manipulate the VB object model to make an add-in very much in the same way that you manipulate the Microsoft Word object model when you write a macro that manipulates the user interface for the word processing application.

(For more information about object models, see Chapter 25, "Using VBA to Connect Your VB Programs with Microsoft Office," Chapter 26, "Making Object-Oriented Programs with Visual Basic," and Chapter 27, "Creating Your Own ActiveX Controls with Visual Basic.")

The object model is complex and comprehensive. Luckily, the Connect Designer add-in (Connect.dsr) does most of the preliminary work for you. After the designer sets up the framework for you, you have to manipulate only a few objects in the model to get the behaviors that you need in order to declare a procedure and insert a code header within the procedure block.

The objects that you manipulate are CodePane and CodeModule. The CodePane object represents the code window in which you add the code; the CodeModule object is the code that appears in the code window, similar to a module or class file.

The core code that creates the procedure declaration and inserts the code header is found in the function AddHeaderProc() (see Listing 29.1). AddHeaderProc() is a procedure of the frmAddIn form.

LISTING 29.1  29LIST01.TXT--Excerpts from the AddHeaderProc Function

01 Public Function AddHeaderProc(strHeaderFile As String, _
strProcName As String, _
strProcType As String, _
strProcScope As String) As Boolean
02 `*************************************
03 `Function Name:AddHeaderProc
04
05 `
06 `strHeaderFile The path and filename of the file has
07 ` the header template
08 `strProcName: The name of the procedure to make
09 `
10 `strProcType: The type of procedure, Sub or Function
11 `
12 `strProcScope: The scope of the procedure, Private or
13 ` Public
14 `Remarks: If the function is successful, it returns
15 ` True. On an error, this function will
16 ` return a message box reporting the error
17 ` number and description. In addition, the
18 ` function returns False.
19 `History:
20 `Programmer: Bob Reselman
21 `Created: 6/14/98
22 `*************************************
23
24 Dim cm As CodeModule `Code Module Object var
25 Dim cp As VBIDE.CodePane `Code Pane Object var
26 Dim strHeader As String `Header string
27 Dim strBuffer As String `Concatenation buffer
28 Dim strFileName As String `Header template filename
29 Dim strBorder As String `Border characters
30 Dim strProcDim As String `Declaration statement
31 Dim strCreated As String `Created date statement
32 Dim strFirstProcLine As String `First line of the code
33 `header
34 Dim strTemp As String `Another string buffer
35 Dim FileHandle As Integer `File handle var
36
37 On Error GoTo AddHeaderProcErr:
38
39 `Create an object variable for the code pane
40 Set cp = VBInstance.ActiveCodePane
41
42 `Create an object variable for the code module
43 `!!!Remember, the code pane only shows lines of the
44 `code module. The code module is where the actual
45 `code lives!!!!!
46 Set cm = cp.CodeModule
47
48 `Start building the procedure declaration
49 strProcDim = strProcScope & " " & strProcType & " "
50 strProcDim = strProcDim & " " & strProcName & "()"
51 strProcDim = strProcDim
52
...
67 `Get the header template filename
68 strFileName = strHeaderFile
69 FileHandle = FreeFile()
70
71 `Open the file
72 Open strFileName For Input As #FileHandle%
73
74 `Make the mouse pointer an hourglass
75 MousePointer = vbHourglass
76
77 `Traverse the lines of the file
78 Do While Not EOF(FileHandle%) ` Check for end of file.
79 `Read a line of the file
80 ` Read line of data.
81 Line Input #FileHandle%, strTemp
82 `Add the line from the output buffer to the text string
83 strHeader = strHeader & strTemp & vbCrLf
84 Loop
...
89 `Close the file once you have had your way with it
90 Close #FileHandle%
91
92 `Add the header file template to the string buffer
93 strBuffer = strBuffer & strHeader
...
103 `Add the End statement for the end of the procedure
104 strBuffer = strBuffer & "End " & strProcType
105
106 `Insert the procedure and header into the code page
107 Call cm.InsertLines(cm.CountOfLines + 1, strBuffer)
108
109 `Hide the Add-In
110 Connect.Hide
111
112 `Set the top line of the pane to the last line
113 cp.TopLine = cm.ProcStartLine(strProcName, _
vbext_pk_Proc)
114
115 `Return a success value
116 AddHeaderProc = True
117
118 `Exit the function; things are good!
119 Exit Function
120 AddHeaderProcErr:
..
126 MsgBox ErrMsg$, vbCritical, Err.Source
127 End Function

Notice that line 40 sets a CodePane object variable to the active code pane. Line 46 assigns the CodeModule object variable to the code module associated with the active code pane by calling CodePane's CodeModule property.

After all the object variables are set, the function goes about constructing the code procedure declaration and code header. Lines 48-52 construct the declaration lines of the procedure. Code that isn't shown (but is available on the Web site) adds the header border and constructs the first line of the header.

Lines 53-72 open the text file that has the header template, cycles through all the lines within the text file, and concatenates the retrieved lines (strTemp) onto the header string (strHeader). Line 75 concatenates the constructed header (strHeader) onto the overall string buffer, strBuffer. Line 77 creates the End procedure line.

After the procedure declaration and procedure header are constructed, they must be inserted in the code module. The procedure declaration and procedure header are one very big string. This string is inserted one line beyond the last line of code in the code module. Inserting the code is accomplished by using the InsertLines() method of the CodeModule object variable on line 80. InsertLines() takes two arguments: the location of the line in which to insert the code and the string to insert. The location is determined by going one line beyond the total number of lines in the code module, as determined by the value returned by the CodeModule's CountOfLines property (CountOfLines +1, as shown on line 80). The string to insert is the buffer that contains the procedure declaration and procedure header (strBuffer).

Line 80 inserts the procedure and procedure header, but you might not be able to see it if the code pane is set to the top lines or some other spot outside the viewing area of the code pane. Therefore, the code pane needs to be adjusted to show the first line of code of the newly inserted procedure. Line 86 resets the top line of the code pane to be the first line of code in the newly inserted procedure. The CodeModule object has a method, ProcStartLine(), that allows you to determine the starting line of a procedure. ProcStartLine() takes two arguments: the name of the procedure from which to determine the first line and a constant that communicates the procedure kind. The method returns a Long that's the first line of the procedure within the code pane. On line 86, the add-in passes in the string variable that represents the procedure and the constant vbext_pk_Proc, which communicates that the procedure kind is a procedure. (You can use the Object Browser to look up all the values that go with the Enum, vbext_ProcKind.)

If everything is successful, the function returns True. If for some reason an error occurs, control is passed to the AddHeaderProcErr code label for error processing.

Granted, this discussion is very high level for creating a custom add-in. You might want to take some time to make a detailed study of all the code involved in making such a tool. As you study the code, you'll see how to use the Office.CommandBarControl object's PasteFace method to add an icon bitmap to the submenu entry, as shown in Figure 29.27. You'll also learn how to test to make sure that a code window is indeed open. Otherwise, you'll be blindly adding procedures to code panes you can't see. Finally, you'll see how to build on the code and graphical framework that the add-in's Connect Designer provides. For an exhaustive discussion of the Visual Basic Object Model (also known as the VB IDE Extensibility Model), look at the documentation that comes with your copy of Visual Basic.

FIGURE 29.27 The ProcHeader add-in submenu item has a bitmap icon that identifies it.


Previous chapterNext chapterContents

© Copyright, Macmillan Computer Publishing. All rights reserved.