Visual Basic


Subclassing objects and procedures is a powerful technique you can build into your template to change the way that standard Visual Basic elements work. You could, for example, subclass Visual Basic's Load method. "Why would I want to do this?" you ask. Well, imagine an application with a complex-state engine that must control what forms can be loaded depending on application state (not an uncommon requirement). By subclassing the Load method, you will effectively channel every load request via your function. You can then determine what is being loaded and either prevent the load from occurring, or permit it. In effect, all the state code is in a single place. Programmers need not worry if it is safe to load a particular object-they just make the call as normal and the subclassed method takes care of the rest. Couple this into your menu control logic and you have the potential to control your application state from a single point! You can subclass many other Visual Basic elements. I will explain how to do this in more detail later in the chapter.

Now you should have a few ideas to start with. Remember that building an application template is a task that should be treated as a project in its own right. Time and budget will need to be allocated for the task; therefore, it makes sense to pin down the requirements beforehand. The success of your template will very much depend on the thought that has gone into its design. In the following sections, I will explain how to perform some of the tasks we have described so far.

Subclassing Functions and Subroutines

To fully understand how subclassing works, you have to understand how Visual Basic resolves which version of a function or subroutine to execute. When Visual Basic encounters a statement such as Call MySub, it begins a search for the MySub definition.

First it looks within the current module, form, or class module for a definition of MySub. If it fails to find one, it looks through the rest of the project for a public (or friend) definition of MySub. Failing that, it goes to the list of project references (available by choosing References from the Project menu) and resolves each reference in order until it finds the first reference that contains a public definition of MySub.

If you check the project references for any project, the first three items in the list you will see are Visual Basic For Applications, Visual Basic Runtime Objects And Procedures, and Visual Basic Objects And Procedures. Because these references contain the definitions for all the intrinsic Visual Basic subroutines, functions, and objects, you will see that, following the rules of the previous paragraph, it is theoretically possible to define local versions of any intrinsic Visual Basic subroutine, function, or object within the program. Unfortunately, this is not the case, as there are some functions that cannot be subclassed for various reasons that I will discuss later in the chapter.