Some Subclassing Tips

As we’ve seen, subclassing involves creating a particular kind of callback function, one that is called by a window’s event loop. Hence, the general tips that we’ve presented for callback functions (such as defining the callback as a Public function in a BAS module and using On Error Resume Next for error handling in the callback function) apply as well to subclassed window procedures. In addition, though, two tips and pitfalls that are unique to subclassing are worth mentioning.

First, remember that all messages for a window are passed through its subclassed window procedure. As a result, the subclassed window procedure (as well as a hook’s filter function) can potentially be called hundreds or even thousands of times per second. If large amounts of code are executed in the window procedure for many of the messages, the performance of the application will degrade considerably. This makes it critically important to avoid doing too much work within a callback function. Performing file I/O in either type of procedure is one type of operation that could take up an unusually long amount of time to finish because of relatively slow disk access. If such long processes are included within these callback functions, the results could be less than satisfactory.

Tip

Do as little work as possible in the subclassed window procedure.

Second, never use the DoEvents function inside the window procedure. DoEvents will halt processing to allow other queued messages to be processed. Using this function inside a window procedure stops processing for that particular message. The problem occurs when a new message is sent to the window procedure before the previous message can finish processing. The first message yields to the second message, the second message yields to the third message, and so on. The outcome of this is unpredictable because messages might be processed out of order, or not be processed at all.

Warning

Do not use the DoEvents function within any window procedure.

Finally, stepping through a subclassing application in break mode from within the VB IDE is problematic. Doing so can cause the application, as well as the VB IDE, to freeze. This makes it much more difficult to debug these types of applications. Debugging applications using subclassing is discussed in depth in Chapter 8.

Warning

Stepping through a subclassing application in the IDE can be problematic.

Get Subclassing and Hooking with Visual Basic now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.