Sign In
Link to us
Home
1. Introduction
2. Introducing VB
3. Projects
4. Containers
5. Controls
6. Code
7. Forms
8. Debugging Code
9. Error Handling
10. Objects
11. User Controls
 11.1 Creating
 11.2 Properties
 11.3 Testing
 11.4 Using a Client

12. Data Projects
13. API
14. Distribution

Other Resources


Affiliated Links:
www.freefunfings.com


11. User Controls

User Controls (also known as ActiveX controls) are bespoke objects that are written in a development environment, such as Visual Basic or Visual C++. Once compiled and made, these objects can then be used in any client application that supports ActiveX.

ActiveX controls can be developed to take mundane or repetitive tasks from of the client application. For example, an HMI application could use an ActiveX to plot and print-out trend data.

Third party ActiveXs often carry licensing requirements, so that they cannot be used in Visual Basic without an appropriate software key or license.

When you develop ActiveX controls in Visual Basic, you can use the existing controls (and any other ActiveX controls that you have loaded) to create your new ActiveX. This is called 'Superclassing' because all of the classes which exist in the component controls will exist in the eventual ActiveX, albeit at a lower level.

11.1 Creating

An ActiveX is created in a similar way as a "Standard EXE" program. The main difference is that the ActiveX cannot run on it's own - it needs a container. By default in Visual Basic, when you run an ActiveX project, it runs in Internet Explorer.

You can make it run in a client Form by adding a form to the project and placing a copy of your ActiveX control onto it.

Exercise xvi:
In this example, we will create an ActiveX which can browse the system to get a file name:

  • Create a new "Standard EXE" and add a User Control from the "Project " menu.
  • In the Project Explorer Window double click the User Control to open the View Object window.
Note:  Notice that the User Control looks a bit like a Form - it can actually contain other controls, as we will see.
  • Change the "Name" property of the User Control to "GetFile". Add the following controls to the User Control in just the same way as you added them to a Form - place the controls in A LOGICAL ORDER:

    DriveListBox
    DirListBox
    FileListBox

  • When the user clicks the DriveListBox, we need to update the DirListBox to reflect the change. Similarly, when the user clicks the DirListBox we need to update the FileListBox to reflect this change. Add the following code to the User Control to ensure that changes are rippled through the controls:
Private Sub Drive1_Change()
    Dir1.Path = Drive1.Drive
End Sub

Private Sub Dir1_Change()
    File1.Path = Dir1.Path
End Sub
  • Now add a TextBox and a CommandButton to the User Control. When the user clicks the FileListBox, the currently selected file name will be placed into the TextBox.
  • The CommandButton will be used to confirm the selection. Change the CommandButton's "Enabled" property to "False", so that the user cannot confirm when the CommandButton is disabled. Add the following:
Private Sub File1_Click()
Dim strPath As String
    strPath = File1.Path
    If Right(strPath, 1) <> "\" Then strPath = strPath & "\"
    strPath = strPath & File1.FileName
    Text1.Text = strPath
End Sub

Private Sub Text1_Change()
    If Text1.Text = "" Then
        Command1.Enabled = False
    Else
        Command1.Enabled = True
    End If
End Sub
Note:  The Right function is used to return a set number of characters from the right-hand side of a String type variable. In this case, we want to check if the variable "strPath" already has a "\" character at the end. If it hasn't, we must add one before adding the actual filename. The path should then make sense.
  • When the user selects a file from the DriveListBox, DirListBox and FileListBox or types a path into the TextBox, the Change Event of the TextBox is raised, allowing you to check the contents. If there is something in the TextBox, the CommandButton can be enabled.
  • Now we have to decide how to get the file to the client when the user clicks the CommandButton. This can be done easily by declaring a new Event. We will call the Event "AcceptFile" and give it a String data type parameter called "Path", which will be used to contain the file's path.
  • Add the following line to the top of the User Control's Code View window - this is the "General Declarations" part of the code module:
Event AcceptFile(Path As String)
  • Now double-click the CommandButton to open the Click Event method, and raise the Event:
Private Sub Command1_Click()
    RaiseEvent AcceptFile(Text1.Text)
End Sub
  • Save the User Control and close the Code and Object View windows. Now open the Form in the Object View window.
  • Notice that there is a new tool in the Toolbox.
    This is your User Control.

  • Add an instance of the User Control to the Form in the same way you would with other controls, but make it invisible by setting it's "Visible" property to "False". Also add a TextBox and a CommandButton, changing the "Caption" property of the CommandButton to "Bro&wse."
  • Double-click the CommandButton to open the Click Event method and programmatically make the User Control visible when this CommandButton is clicked.
  • Now double-click the User Control -it should open into the User Control's AcceptFile Event, as you defined above. In this event, you are passed a file's path. Programmatically pass this into the TextBox on the Form when the user selects a file from the User Control, then make the User Control invisible again, ready for the next time we need it.
Test the application. Experiment with two or three instances of the GetFile control.

11.2 Properties

11.2.1 Property Wizard Add-in
In the previous exercise, we saw how to create an Event within an ActiveX and how to pass parameters to a client application. The new ActiveX also has some properties that can be seen in the Properties Window when an instance of it is selected in the Form. These properties are the default ones that Visual Basic assigns to every User Control that is developed.

In the same way that we have 'Superclassed' some of the controls in the User Control, we can also 'Superclass' the existing properties and methods and create new ones. Properties can be created individually, using the Property Let and Property Get methods described earlier, but there is an easier automated way - using an Add-In.

An Add-In is a small program that sits behind Visual Basic and when called upon, performs some tasks that speed up development in some way.

Check that the Add-In is loaded:

Exercise:
  • Select "Add-In Manager" on the "Add-Ins" menu. This should bring up a dialogue box with a list of available Add-Ins.
  • In the list, select "VB 6 ActiveX Ctrl Interface Wizard" and tick the "Loaded/Unloaded" and "Load on Startup" options in the "Load Behavior" frame.
  • Click "OK" to close the dialogue.
  • Check that there is a new option in the "Add-Ins" menu called "ActiveX Control Interface Wizard.".

In the User Control's Object View window, we can see that the ActiveX has various properties that don't appear in the instance we placed on the Form, such as "BackColor", "ForeColor" and "Font". We will add these properties and an additional custom one called "FilePath" that we will use to pre-load the TextBox on the ActiveX with an existing filename:

Exercise xvii:
  • Open the User Control's Object View window and select "ActiveX Control Interface Wizard." from the "Add-Ins" menu. A dialogue box will appear.
  • Click "Next" on the Introduction page. You will then be shown two lists of properties. The list on the left is all available properties. The list on the right is used properties. For each of the following, select the property in the list on the left and click the ">" button to add it to your ActiveX:

    BackColor
    Font
    ForeColor

  • Click the "Next" button to accept the properties. You will then see a list of custom properties, events and methods.
Note:  Notice that the "AcceptFile" Event is already in the list, because we added it manually, however it is still a custom Event.
  • Click the "New" button to add a property. When the "Add Custom Member" dialogue appears, enter the property name as "FilePath" and make sure that the "Property" option is selected. Then click "OK".
  • Back in the custom properties, events and methods dialogue, click "Next". You will then be asked to 'map' the new properties to existing ones, if you require. Select each of the standard properties and map them to the User Control's existing property with the same name. Map the new "FilePath" property to the "Text" member of the "Text1" control.
  • Leave the "AcceptFile" event as it is and click "Next".
  • The next stage is to declare the data types for your custom properties, events or methods. Since "AcceptFile" has already been declared manually, we need do nothing here.
  • Click the "Next" button (or "Finish" if you don't want to see the Wizard's Summary Report). You can then view the Summary Report and/or finish.
Open the User Control in the Code View window. Read through the new portions of code and try to understand what they do.

  • Save the User Control and close the Object and Code View windows. Open the Form's Object View window and select the instance of the "GetFile" ActiveX.
Note:  Notice that in the Properties Window, the "BackColor", "ForeColor" and "Font" are now available. In addition our custom property "FilePath" is there.
  • Type some default text into the "FilePath" property (eg "C:\MyFile.txt"). Press enter to accept the change.
This property now gives us access to the TextBox on the ActiveX all of the time, rather than just when the "AcceptFile" event is raised.

Test the application.


11.2.2 Property Pages
The properties that exist within a User Control can be added to a series of Property Pages. These pages are just an alternative way of accessing the object's properties during the design time environment. Customised properties can also be inserted onto a page quite easily.

Once created, a property page will provide a dialogue interface which the user sees when the User Control's "Properties" option is selected from the pop-up menu that appears if you right-click on it.

The easiest way of adding Property Pages is using the Wizard provided by Visual Basic, through the "Add Property Pages" option of the "Project" menu.

11.2.3 Accessing ActiveXs in the Container
An ActiveX doesn't necessarily need to have any graphical elements. It can exist as modules of code and declarations. These are similar to using external Dynamic Link Libraries (".DLLs"), but exist as objects within the client code.

Since ActiveXs are objects, they can be used to declare instances in the client application. These instances can then have their properties, events and methods accessed using the dot (".") modifier, as normal.

11.3 Testing

In the exercise we have done, the User Control exists within the same project as the Form, so there is no need to make a reference to it. If we developed a totally separate ActiveX, we would need to Make it into an ".ocx" file, then refer to it from our client project.

Exercise xviii:
  • Re-open the last exercise project and remove the Form by right-clicking on it in the Project Explorer and selecting "Remove Form1.frm".
  • If you try to run the project now, you will get an error because an ActiveX cannot run on it's own - it has to have a client application. To tell Visual Basic that the current project is now an ActiveX, select "Project1 Properties." from the "Project" menu. On the dialogue that appears, change the "Project Type" entry on the "General" tab to "ActiveX Control" and the "Startup Object" to "None". Click "OK" to any prompts.
  • To make the ActiveX Public (so that any compatible client application can hold it) set the "Public" property of the ActiveX to "True".
  • Run the project as normal (F5) and click "OK" on any dialogues.
Test the ActiveX inside the Internet Browser.

  • Make your ActiveX, by selecting the ActiveX in the Project Explorer window and selecting "Make Project1.ocx" from the "File" menu. Change the default file name to "GetFile.ocx".

11.4 Using a Client

11.4.1 Class ID
Each time Visual Basic makes an ActiveX, it generates a random 32-digit number that is used by Windows to refer to that particular ActiveX. This unique number is called the Class Identification number or Class ID.

Exercise:
  • Run the project from the exercise above so that the Internet Browser opens with the ActiveX in.
  • Select the "Source" option from the "View" menu to reveal the Hypertext Markup Language (HTML) code for the page.
Note:  In this code, you will see that the ActiveX object is declared with an HTML "<OBJECT>" tag. Inside this object tag, the HTML code indicates the Class ID of the ActiveX, so that the browser can refer back to Windows for the ActiveX control, so that it can be displayed.

We need to refer back to this file later, so save the HTML file onto the Windows desktop:

  • Select "Save As." from the File menu. On the "Save As" dialogue box, navigate to the desktop.
  • Make sure that the "Save as type" box is changed to "All Files" and type "ActiveXTest.html" into the "File name" box. Click "Save".
  • Once saved, this HTML file can be viewed in the browser at any time by double-clicking it in on the Windows desktop.

11.4.2 Windows Registration
11.4.2.1 The Registry
Since we have developed an ActiveX, client applications will refer to the Class ID in order for Windows to display the correct object. Windows therefore needs to have some kind of 'look-up' that cross-references the Class ID with the object. This is done inside the Windows Registry.

The Registry is a file within Windows that is used to store settings and configuration data for various applications that are installed. Each time you install an ActiveX (or other objects e.g. Dynamic Link Library), an entry is made in the Registry stating the ActiveX's filename (".ocx"), path and corresponding Class ID number.

Exercise:
Make sure that you have Made the ActiveX in "Exercise xviii" before starting this exercise.

Note:  The Registry structure differs between different versions of Windows, so some of the values seen below may differ slightly. These values were taken from MicrosoftT Windows NT4.0 Workstation.
  • Select "Run." from the Windows "Start" button menu.
  • In the box, type in "regedit" and click "OK". "Regedit" is a program that allows you to see the Windows Registry entries.
  • Once "Regedit" has opened, select "Find." from the "Edit" menu (or press Ctrl+F). This will bring up a dialogue box asking what text you would like to find.
  • Type "GetFile" into the Find dialogue and click the "Find Next" button. Regedit will then try to find the text in the Registry.
  • After a few seconds, Regedit should find the entry for our ActiveX control. At the bottom of the window, the status bar should read "My Computer\HKEY_CLASSES_ROOT\CLSID\" followed by the Class ID.
  • Check that this is the same Class ID number as the one we saw in the HTML file above. This verifies that the Class ID reference that we are using corresponds to the correct ActiveX, but where is the ".ocx" file stored?
  • Press F3 to resume the "Find" operation. The next entry for "GetFile" should be inside a sub-folder and should contain a value called "(Default)" which contains the path to our "GetFile.ocx" file.

11.4.2.2 Registering Controls and Libraries
One obvious problem with the system above, is that if the ActiveX (or other object) is distributed to other computers, they will not have any reference to the Class ID in their Registries. There are two ways that this can be done.

When the application is being installed. Rather than simply copying the ".ocx" file across to the other computer, an installation "Setup" is generated. This "Setup" program performs all of the copying and then Registers all of the controls and libraries on the computer. If you have ever installed any large applications, you may have noticed that it says like "Setup is now updating your system" towards the end of the installation; this usually means that the application is Registrering all of it's controls and libraries.

Windows contains a program called "Registry Server 32" that can Register your controls or libraries for you. The command line syntax for this program is as follows:

regsvr32 path-to-file

A control or library can also be Unregistered with Registry Server 32 as follows:

regsvr32 /U path-to-file

Exercise:
Make sure that you have Made the ActiveX in "Exercise xviii" before starting this exercise.

This is an easier way to register controls and libraries:

  • Select "Find-Files or Folders." from the Windows "Start" button menu. On the dialogue box enter "regsvr32.exe" as the search text and change the "Look in" field to your C drive. Click "Find Now".
  • When the file has been found, drag it onto your Desktop to create a shortcut.
  • Navigate to where you Made your "GetFile.ocx" control. Drag the "GetFile.ocx" file onto the shortcut to "RegSvr32" that you just made (this is the equivalent of running the RegSvr32 program with the ".ocx" file as a command line parameter).
  • Once "RegSvr32" has registered the control, it will report back to say whether Registration was successful.

11.4.3 Binary Compatibility
As we learned earlier, each time an ActiveX is Made, it is given a unique Class ID. When we are developing large applications that use ActiveXs, we may choose to develop the ActiveXs separately. This gives us a problem, because each time we modify the ActiveX and Make it, the main project cannot find the reference to the version of the ActiveX that it was developed with, so generates an error.

In order to stop this from happening, we can force Visual Basic to use the same Class ID each time it Makes the ActiveX. This is called Binary Compatibility, as each new version is compatible with all previous versions.

Exercise xix:
Make sure that you have Made the ActiveX in "Exercise xviii" before starting this exercise.

  • Re-Open the "GetFile" ActiveX project and select "Project1 Properties" from the "Project" menu. Select the "Component" tab on the dialogue box.
  • Change the "Version Compatibility" to "Binary Compatibility" and click the browse button ("."). Navigate to the "GetFile.ocx" file that you Made earlier and click "Open".
  • Click "OK" on the dialogue box.
Note:  Each time you Make the ActiveX, it will re-use the Class ID as specified in the "GetFile.ocx" file that you selected in the "Project Properties" dialogue box.
  • Change the background colour of your ActiveX to bright red (so that we can easily tell that it has changed). Make the ActiveX again by selecting "Make GetFile.ocx" from the "File" menu, accepting the prompt to overwrite it.
  • Exit Visual Basic and run the HTML file that you saved to the desktop earlier - this file should still contain the Class ID from the first version of your ActiveX.
Note:  Note that the Internet Browser can still find your ActiveX, even though you have changed it because the Class ID is still the same.

<<Page 10  :   Top  :   Page 12>>
©vbtraining.co.uk