Visual Basic/Subclassing

Subclassing can be useful when you want to add functionality that is not directly supported by Visual Basic. To explain how this works we must first go through a little background theory.

All windows in Windows (for example a form, a button, a listbox, etc.) have a function that the operating system or other programs can call to communicate with the program. Windows can, for example, send messages about events such as the mouse pointer moving over the window, a key being pressed when the window has the focus and much more. Programs can also send messages that ask for information about the window; for example, the EM_GETLINECOUNT message asks a textbox to send back the number of lines in the text it holds. One can also define one's own functions.

To call these special functions you can use PostMessage, SendMessage or CallWindowProc (the last only if you know the address of the function).

Usually such a procedure looks something like this:

In this function hwnd is the handle of the window that the caller has tried to contact; uMsg is the message identifier which says what the call is about; wParam and lParam are used for whatever purpose the caller and window agree on. The handle, hwnd, is not an address but is used by Windows to find the address.

If, for example, we want to set the text that appears on the title bar of a form we can use the following code:

Why Subclass
What is the point of subclassing?

Using this technique we can completely replace a program's own window function with our own. Then we can respond to the messages in ways that Visual Basic doesn't, we can decide to send the messages further to the original window function or not as we like, modifying them on the way in any way we please.

Example
To specify that our window function is to be used we use the API call SetWindowLong. Study the following example and put it in a base module:

Add a form with a button cmdTest and add this code:

When you click the cmdTest button, you'll see that the text that appears is not "This is a test", but "Subclassing".