Referencing an Object

Tuesday Nov 19th 2002 by Neil Avent
Share:

Referencing An Object

This is a basic tutorial to explain how you can harness the power of your Office applications to add some 'panache' to your own Visual Basic Project.

In the next few articles I will be explaining how you can instance various classes into your Visual Basic Projects which can incorporate the functionality of Word, Excel, Access and many other applications into your projects.

This article will deal with finding a class, referencing it to your project and finally a quick discussion on various binding methods. Subsequent articles will deal with the applications that make up the Office product range. Throughout this series I will explain how to interact with Office 97. The code is also compatible with Office 2000, the latest version of the suite.

The references Dialog Box details all available object libraries that are listed in your registry and can be referenced in your project. All the items with a tick in the selection box are already in your project. If you add a tick to an item then that reference can be used to create an object allowing you to access its properties, methods, events and constants.

Lets take a quick look at adding a reference and then creating it as an object in your code so we can see how it adds functionality to our project.

Firstly, lets open the references Dialog Box. This can be found from the drop down menus on your Visual Basic user interface. Open up a new Standard EXE project and then Choose Project and then References as shown in this illustration.

This will then show you the references Dialog Box. You will notice that there are a few items already selected. These references are required by the Visual Basic engine to run correctly, and so can not be removed from the list.

Let's add a reference to your project now. In the future we will be looking at items from the Microsoft Office family but for now let's start with Internet Explorer. If you do not have Internet Explorer 4 or 5 then please download and install it so you can follow the rest of this section.

Scroll down the box until you find Microsoft Internet Controls, and add a tick next to it. Near the bottom of the dialog box you will see the filename being referenced. This file must reside on every computer where your application is installed, or the reference will fail. Now click on OK and you are returned to your Visual Basic interface.

So how do you know what properties, methods, events and constants have been added to our project by referencing this object? Press F2 to bring up your Object Browser. In the top left of the Object Browser, select SHDocVw (the name of the file we just referenced). A list of everything contained in SHDocVw will be listed for you to browse through. In this brief tutorial we are only interested in the 'InternetExplorer' class listed in the left-hand column.

Note: If SHDocVw is not in the drop down list then the Microsoft Internet Controls has not been referenced correctly, so go back to the start of this section and try again.

Close the object browser when you have finished browsing the class and we will have a go at using this class within our code.

Now we can have a go at instancing this class which will give us access to the items contained in it at both design-time and run-time. If you have ever used a class module to do this then you will know what we are going to do next as it is exactly the same procedure.

Close the Object Browser. In the General Declarations for the form add this line.

Dim Withevents IE as InternetExplorer

As you start to type "InternetExplorer" a dropdown box should appear to signify that the object is available for use in your application. This tells you that the object is correctly referenced to your project. This is usually how you would reference any class to your project as it demonstrates Early Binding. I will be explaining Early vs. Late Binding fully in another section. The Withevents keyword in this statement is optional - I have included it here to signify how we can use it, even though it isn't necessary in this demonstration.

If you want to see what events this will possibly generate for this project, then you can look in the drop-down menu as you would for a textbox or any other control on your form. You will notice that all the new events are under IE which is the name we have given to our InternetExplorer Class.

Note: Modules do not handle events, so this code must be used in a form.

Let's see what this InternetExplorer class does for us. Add 3 command buttons to the form. Call them cmdStart, cmdVisible and cmdStop. Then give them suitable captions.

Under cmdStart add the following code for the Click Event.

Set IE = New InternetExplorer
Cmdstart.enabled = False
CmdStop.enabled = True

Under cmdvisible add the following code to the Click Event.

ie.Visible = Not (ie.Visible)

Under cmdQuit add the following code for the Click Event.

ie.Quit
Set ie = Nothing
cmdStart.Enabled = True
cmdVisible.Enabled = False

And finally in the form load event add this:

cmdStop.Enabled = False
cmdVisible.Enabled = False

Then run the project and see what happens. Your form comes up on the screen. Click the start button. You may see your mouse pointer may show the busy icon for a second, then your form loses the focus. Nothing really noticeable has happened though. Now try the visible button, Internet Explorer appears, you can toggle it by repeatedly clicking on the Visible button. You can also use Internet Explorer as you usually would. Clicking on Stop closes it down.

That's not bad for a few lines of code is it? Especially as more than half of your code was making buttons enabled at various times. You have just created your first object! In the next section, I will explain the code in more detail to help you understand what is going on.

Someone who looks at this project without understanding the code might be under the impression that you have just loaded Internet Explorer and added a bit of code to hide it.

From a visible point, you could see why they would think that, but the underlying code is far more intelligent. If we started Internet Explorer from a Shell call, and used subclassing to hide the window, we could easily gain the same effect as this example. However, this method of exposing Internet Explorer as an object instead of an application puts us in a far more powerful position when it comes to controlling and understanding what it is doing.

We have 3 command buttons on our form, lets look at each one and what they do.

Under cmdStart we have the following code:

Private Sub cmdStart_Click()
    Set ie = New InternetExplorer
    cmdStart.Enabled = False
    cmdVisible.Enabled = True
    cmdStop.Enabled = True
End Sub

So when you clicked on the Start command button the following happened.

  • IE was set to a new instance of the InternetExplorer class
  • The cmdStart button was disabled so the user could not click on it again.
  • The cmdVisible and cmdStop buttons were enabled so the user could click on them

It sounds quite straightforward and even after a closer look it remains so. The only bit I will discuss here is the Set Statement. With a datatype, once you have declared the variable (with a Dim statement) you have to place a value into the variable before you get any use out of it. Objects run along the same lines, we used the Dim statement to tell VB what form the object would be but you need the New keyword to actually create an instance of an object. So in this scenario the InternetExplorer class object was exposed to us at design time even though we didn't run it until the Start button was clicked.

Under the cmdVisible button we have this code:

Private Sub cmdVisible_Click()
    ie.Visible = Not (ie.Visible)
End Sub

This toggles the visible property of the IE class. I found out that the visible property was available by looking at the value in the Object Browser. By default, any object created is not visible so when using them in your projects it is good practice to make them visible, especially when debugging.

The final command button was cmdStop, which has this code:

Private Sub cmdStop_Click()
    ie.Quit
    Set ie = Nothing
    cmdStart.Enabled = True
    cmdVisible.Enabled = False
End Sub

This runs the quit method contained in the InternetExplorer class, clears the pointer to the class from your project and finally sets the enabled states of your buttons.

We close the class this way to release system resources that can be used by other applications. The Quit method closes the InternetExplorer window and the Set statement clears the pointer from your project. If the quit method was not run the pointer would have been cleared and the Internet Explorer interface would have been left running regardless of whether it was visible or not. This could be used in an instance where you want your program to stop running but leave Internet Explorer going. Once the pointer had been cleared Internet Explorer would be waiting for a response from the user.

Now we have seen what each of the command buttons have done let us take a look at the first statement we added to our code for this project.

Dim IE WithEvents As InternetExplorer

Well, we all have a good understanding of what the Dim statement does. In this case it is preparing the variable IE to point to an Object rather than a DataType. We have also specified the Object as InternetExplorer. The WithEvents keyword also exposes the form containing this declaration to any Events the InternetExplorer class may raise.

We could have used:

Dim IE As Object

We would still have been giving Visual Basic enough information to run the project successfully. Try amending the line to this shorter version and re-running the project. Everything seems to function as before. So why did we bother specifying the InternetExplorer class?

That is a valid question. Let's have a look and see why I told you to write the code that specified the InternetExplorer class in the Dim statement. One benefit we have immediately lost from declaring IE as any Object rather than the InternetExplorer Class Object is the events. You cannot declare WithEvents unless you specifically state what Class Object will be raising events.

There is a little more to it than that though. When you was working through the code before the standard object list appeared once you had typed in "IE." this stops as well once only a generic Object is declared. This can make the task of interrogating properties of the Object and executing its methods a little more tricky.

So why does the Visual Basic Interface do that? After all it knows the Class name from the Set statement under the cmdStart click event. The reason for this is that IE is set at design time to the datatype or object you are declaring. This way in the design time environment you can benefit from the standard help and formatting whilst you are typing which makes your job as a developer a lot easier. This is also known as early binding, as the object is bound to you early at design time instead of late at run time. Early binding is far more optimized than Late binding due to the nature of the project being able to deduce what to do before execution.

I am going to try and summarise all this as much as possible but a lot of ground has been covered in this article. Whether you fully understand what I have done and why I have done it comes down to how you perceive what an Object is and what you can do with it.

For those of you who have not tried anything like this before, then the idea of actually creating an instance of Internet Explorer as an object instead of a new task may be quite alien. But if you sit back and look at the reasoning and benefits gained it should begin to make sense. The principles given here can be applied to many other applications or objects. The main points you should take away from this article are the difference between Early and Late binding and closing the object properly.

Just to bring the point home again, Early Binding is where you declare what type of object you wish to create rather than just an object waiting to see what it is set to before knowing what shape to take. You will know if you have a successfully created Early Binding between the object and your project because Events will be available if you declared WithEvents and you will have the Methods, properties and constants available to you whilst in the code window.

I have never come across a situation where I have needed Late Binding (someone is bound to prove me wrong here!) and in larger projects you lose so much efficiency and speed it is not worth it.

In the next article we will be examining the Word Object Library and using it to create something with some use. It is not that hard to add a text box and use it to navigate your InternetExplorer class. Have a go at doing that and play with some of the properties, you can do some things you cannot do to it whilst it is running as a standalone application.

Share:
Home
Mobile Site | Full Site
Copyright 2017 © QuinStreet Inc. All Rights Reserved