Windows API Functions: Appendix
Windows API Functions: Appendix
Windows API
Functions
The Visual Basic language provides a rich set of functions, commands, and objects,
but in many cases they don’t meet all the needs of a professional programmer. Just
to name a few shortcomings, Visual Basic doesn’t allow you to retrieve system infor-
mation—such as the name of the current user—and most Visual Basic controls ex-
pose only a fraction of the features that they potentially have.
Expert programmers have learned to overcome most of these limitations by di-
rectly calling one or more Windows API functions. In this book, I’ve resorted to API
functions on many occasions, and it’s time to give these functions the attention they
deserve. In contrast to my practice in most other chapters in this book, however,
I won’t even try to exhaustively describe all you can do with this programming tech-
nique, for one simple reason: The Windows operating system exposes several thou-
sand functions, and the number grows almost weekly.
Instead, I’ll give you some ready-to-use routines that perform specific tasks and
that remedy a few of the deficiencies of Visual Basic. You won’t see much theory in
these pages because there are many other good sources of information available, such
as the Microsoft Developer Network (MSDN), a product that should always have a
place on the desktop of any serious developer, regardless of his or her programming
language.
1189
Appendix
A WORLD OF MESSAGES
The Microsoft Windows operating system is heavily based on messages. For example,
when the user closes a window, the operating system sends the window a WM_CLOSE
message. When the user types a key, the window that has the focus receives a
WM_CHAR message, and so on. (In this context, the term window refers to both top-
level windows and child controls.) Messages can also be sent to a window or a con-
trol to affect its appearance or behavior or to retrieve the information it contains. For
example, you can send the WM_SETTEXT message to most windows and controls
to assign a string to their contents, and you can send the WM_GETTEXT message to
read their current contents. By means of these messages, you can set or read the
caption of a top-level window or set or read the Text property of a TextBox control,
just to name a few common uses for this technique.
Broadly speaking, messages belong to one of two families: They’re control mes-
sages or notification messages. Control messages are sent by an application to a win-
dow or a control to set or retrieve its contents, or to modify its behavior or appearance.
Notification messages are sent by the operating system to windows or controls as the
result of the actions users perform on them.
Visual Basic greatly simplifies the programming of Windows applications because
it automatically translates most of these messages into properties, methods, and events.
Instead of using WM_SETTEXT and WM_GETTEXT messages, Visual Basic program-
mers can reason in terms of Caption and Text properties. Nor do they have to worry
about trapping WM_CLOSE messages sent to a form because the Visual Basic runtime
automatically translates them into Form_Unload events. More generally, control mes-
sages map to properties and methods, whereas notification messages map to events.
Not all messages are processed in this way, though. For example, the TextBox
control has built-in undo capabilities, but they aren’t exposed as properties or methods
by Visual Basic, and therefore they can’t be accessed by “pure” Visual Basic code.
(In this appendix, pure Visual Basic means code that doesn’t rely on external API func-
tions.) Here’s another example: When the user moves a form, Windows sends the
form a WM_MOVE message, but the Visual Basic runtime traps that message with-
out raising an event. If your application needs to know when one of its windows
moves, you’re out of luck.
By using API functions, you can work around these limitations. In this section,
I’ll show you how you can send a control message to a window or a control to af-
fect its appearance or behavior, while in the “Callback and Subclassing” section, I’ll
illustrate a more complex programming technique, called window subclassing, which
lets you intercept the notification messages that Visual Basic doesn’t translate to events.
1190
Appendix Windows API Functions
Before you can use an API function, you must tell Visual Basic the name of the
DLL that contains it and the type of each argument. You do this with a Declare state-
ment, which must appear in the declaration section of a module. Declare statements
must be declared as Private in all types of modules except BAS modules (which also
accept Public Declare statements that are visible from the entire application). For
additional information about the Declare statement, see the language documentation.
The main API function that you can use to send a message to a form or a control
is SendMessage, whose Declare statement is this:
Private Declare Function SendMessage Lib “user32” Alias “SendMessageA” _
(ByVal hWnd As Long, ByVal wMsg As Long, _
ByVal wParam As Long, lParam As Any) As Long
The hWnd argument is the handle of the window to which you’re sending the
message (it corresponds to the window’s hWnd property), wMsg is the message
number (usually expressed as a symbolic constant), and the meaning of the wParam
and lParam values depend on the particular message you’re sending. Notice that
lParam is declared with the As Any clause so that you can pass virtually anything to
this argument, including any simple data type or a UDT. To reduce the risk of acci-
dentally sending invalid data, I’ve prepared a version of the SendMessage function,
which accepts a Long number by value, and another version that expects a String
passed by value. These are the so called type-safe Declare statements:
Private Declare Function SendMessageByVal Lib “user32” _
Alias “SendMessageA” (ByVal hWnd As Long, ByVal wMsg As Long, _
ByVal wParam As Long, Byval lParam As Long) As Long
Apart from such type-safe variants, the Declare functions used in this chapter,
as well as the values of message symbolic constants, can be obtained by running the
API Viewer utility that comes with Visual Basic. (See Figure A-1 on the following page.)
CAUTION When working with API functions, you’re in direct touch with the
operating system and aren’t using the safety net that Visual Basic offers. If you
make an error in the declaration or execution of an API function, you’re likely to
get a General Protection Fault (GPF) or another fatal error that will immediately
shut down the Visual Basic environment. For this reason, you should carefully
double-check the Declare statements and the arguments you pass to an API
function, and you should always save your code before running the project.
1191
Appendix
Figure A-1. The API Viewer utility has been improved in Visual Basic 6 with the
capability to set the scope of Const and Type directives and Declare statements.
NOTE All the examples shown in this appendix are available on the compan-
ion CD. To make the code more easily reusable, I’ve encapsulated all the ex-
amples in Function and Sub routines and stored them in BAS modules. Each
module contains the declaration of the API functions used, as well as the Const
directives that define all the necessary symbolic constants. On the CD, you’ll also
find demonstration programs that show all the routines in action. (See Figure A-2.)
1192
Appendix Windows API Functions
Figure A-2. The program that demonstrates how to use the routines in the TextBox.bas
module.
Notice that the number of columns used for horizontal scrolling might not
correspond to the actual number of characters scrolled if the TextBox control uses a
nonfixed font. Moreover, horizontal scrolling doesn’t work if the ScrollBars property
is set to 2-Vertical. You can scroll the control’s contents to ensure that the caret is visible
using the EM_SCROLLCARET:
SendMessageByVal Text1.hWnd, EM_SCROLLCARET, 0, 0
One of the most annoying limitations of the standard TextBox control is that
there’s no way to find out how longer lines of text are split into multiple lines. Us-
ing the EM_FMTLINES message, you can ask the control to include the so-called soft
line breaks in the string returned by its Text property. A soft line break is the point
where the control splits a line because it’s too long for the control’s width. A soft line
break is represented by the sequence CR-CR-LF. Hard line breaks, points at which
the user has pressed the Enter key, are represented by the CR-LF sequence. When
sending the EM_FMTLINES message, you must pass True in wParam to activate soft
line breaks and False to disable them. I’ve prepared a routine that uses this feature
to fill a String array with all the lines of text, as they appear in the control:
‘ Return an array with all the lines in the control.
‘ If the second optional argument is True, trailing CR-LFs are preserved.
Function GetAllLines(tb As TextBox, Optional KeepHardLineBreaks _
As Boolean) As String()
1193
Appendix
For i = 0 To UBound(result)
If Right$(result(i), 1) = vbCr Then
result(i) = Left$(result(i), Len(result(i)) - 1)
ElseIf KeepHardLineBreaks Then
result(i) = result(i) & vbCrLf
End If
Next
‘ Deactivate soft line breaks.
SendMessageByVal tb.hWnd, EM_FMTLINES, False, 0
GetAllLines = result()
End Function
You can also retrieve one single line of text, using the EM_LINEINDEX message
to determine where the line starts and the EM_LINELENGTH to determine its length.
I’ve prepared a reusable routine that puts these two messages together:
Function GetLine(tb As TextBox, ByVal lineNum As Long) As String
Dim charOffset As Long, lineLen As Long
‘ Retrieve the character offset of the first character of the line.
charOffset = SendMessageByVal(tb.hWnd, EM_LINEINDEX, lineNum, 0)
‘ Now it’s possible to retrieve the length of the line.
lineLen = SendMessageByVal(tb.hWnd, EM_LINELENGTH, charOffset, 0)
‘ Extract the line text.
GetLine = Mid$(tb.Text, charOffset + 1, lineLen)
End Function
Standard TextBox controls use their entire client area for editing. You can retrieve
the dimension of such a formatting rectangle using the EM_GETRECT message, and
you can use EM_SETRECT to modify its size as your needs dictate. In each instance,
you need to include the definition of the RECT structure, which is also used by many
other API functions:
1194
Appendix Windows API Functions
For example, see how you can shrink the formatting rectangle along its hori-
zontal dimension:
Dim Left As Long, Top As Long, Right As Long, Bottom As Long
GetRect tb, Left, Top, Right, Bottom
Left = Left + 10: Right = Right - 10
SetRect tb, Left, Top, Right, Bottom
One last thing that you can do with multiline TextBox controls is to set their
tab stop positions. By default, the tab stops in a TextBox control are set at 32 dialog
units from one stop to the next, where each dialog unit is one-fourth the average
character width. You can modify such default distances using the EM_SETTABSTOPS
message, as follows:
‘ Set the tab stop distance to 20 dialog units
‘ (that is, 5 characters of average width).
SendMessage Text1.hWnd, EM_SETTABSTOPS, 1, 20
You can even control the position of each individual tab stop by passing this
message an array of Long elements in lParam as well as the number of elements in
the array in wParam. Here’s an example:
1195
Appendix
ListBox Controls
Next to TextBox controls, ListBox and ComboBox are the intrinsic controls that benefit
most from the SendMessage API function. In this section, I describe the messages you
can send to a ListBox control. In some situations, you can send a similar message to
the ComboBox control as well to get the same result, even if the numeric value of
the message is different. For example, you can retrieve the height in pixels of an item
in the list portion of these two controls by sending them the LB_GETITEMHEIGHT
(if you’re dealing with a ListBox control) or the CB_GETITEMHEIGHT (if you’re
dealing with a ComboBox control). I’ve encapsulated these two messages in a poly-
morphic routine that works with both types of controls. (See Figure A-3.)
‘ The result of this routine is in pixels.
Function GetItemHeight(ctrl As Control) As Long
Dim uMsg As Long
If TypeOf ctrl Is ListBox Then
uMsg = LB_GETITEMHEIGHT
ElseIf TypeOf ctrl Is ComboBox Then
uMsg = CB_GETITEMHEIGHT
Else
Exit Function
End If
GetItemHeight = SendMessageByVal(ctrl.hwnd, uMsg, 0, 0)
End Function
Figure A-3. The demonstration program for using the SendMessage function with
ListBox and ComboBox controls.
1196
Appendix Windows API Functions
You can also set a different height for the list items by using the LB_
SETITEMHEIGHT or CB_SETITEMHEIGHT message. While the height of an item isn’t
valuable information in itself, it lets you evaluate the number of visible elements in
a ListBox control, data that isn’t exposed as a property of the Visual Basic control.
You can evaluate the number of visible elements by dividing the height of the inter-
nal area of the control—also known as the client area of the control—by the height
of each item. To retrieve the height of the client area, you need another API func-
tion, GetClientRect:
Private Declare Function GetClientRect Lib “user32” (ByVal hWnd As Long, _
lpRect As RECT) As Long
This is the function that puts all the pieces together and returns the number of
items in a ListBox control that are entirely visible:
Function VisibleItems(lb As ListBox) As Long
Dim lpRect As RECT, itemHeight As Long
‘ Get client rectangle area.
GetClientRect lb.hWnd, lpRect
‘ Get the height of each item.
itemHeight = SendMessageByVal(lb.hWnd, LB_GETITEMHEIGHT, 0, 0)
‘ Do the division.
VisibleItems = (lpRect.Bottom - lpRect.Top) \ itemHeight
End Function
You can use this information to determine whether the ListBox control has a
companion vertical scroll bar control:
HasCompanionScrollBar = (Visibleitems(List1) < List1.ListCount)
Windows provides messages for quickly searching for a string among the items
of a ListBox or ComboBox control. More precisely, there are two messages for each
control, one that performs a search for a partial match—that is, the search is successful
if the searched string appears at the beginning of an element in the list portion—and
one that looks for exact matches. You pass the index of the element from which you
start the search to wParam (−1 to start from the beginning), and the string being
searched to lParam by value. The search isn’t case sensitive. Here’s a reusable rou-
tine that encapsulates the four messages and returns the index of the matching ele-
ment or −1 if the search fails. Of course, you can reach the same result with a loop
over the ListBox items, but the API approach is usually faster:
Function FindString(ctrl As Control, ByVal search As String, Optional _
startIndex As Long = -1, Optional ExactMatch As Boolean) As Long
Dim uMsg As Long
If TypeOf ctrl Is ListBox Then
uMsg = IIf(ExactMatch, LB_FINDSTRINGEXACT, LB_FINDSTRING)
(continued)
1197
Appendix
Because the search starts with the element after the startIndex position, you can
easily create a loop that prints all the matching elements:
‘ Print all the elements that begin with the “J” character.
index = -1
Do
index = FindString(List1, “J", index, False)
If index = -1 Then Exit Do
Print List1.List(index)
Loop
A ListBox control can display a horizontal scroll bar if its contents are wider than
its client areas, but this is another capability that isn’t exposed by the Visual Basic
control. To make the horizontal scroll bar appear, you must tell the control that it
contains elements that are wider than its client area. (See Figure A-3.) You do this
using the LB_SETHORIZONTALEXTENT message, which expects a width in pixels
in the wParam argument:
‘ Inform the ListBox control that its contents are 400 pixels wide.
‘ If the control is narrower, a horizontal scroll bar will appear.
SendMessageByVal List1.hwnd, LB_SETHORIZONTALEXTENT, 400, 0
You can add a lot of versatility to standard ListBox controls by setting the posi-
tions of their tab stops. The technique is similar to the one used for TextBox controls.
If you add to that the ability to display a horizontal scroll bar, you see that the ListBox
control becomes a cheap means for displaying tables—you don’t have to resort to
external ActiveX controls. All you have to do is set the tab stop position to a suitable
distance and then add lines of tab-delimited elements, as in the following code:
‘ Create a 3-column table using a ListBox.
‘ The three columns hold 5, 20, and 25 characters of average width.
Dim tabs(1 To 2) As Long
tabs(1) = 20: tabs(2) = 100
SendMessage List1.hWnd, LB_SETTABSTOPS, 2, tabs(1)
‘ Add a horizontal scroll bar, if necessary.
SendMessageByVal List1.hwnd, LB_SETHORIZONTALEXTENT, 400, 0
List1.AddItem “1” & vbTab & “John” & vbTab & “Smith"
List1.AddItem “2” & vbTab & “Robert” & vbTab & “Doe"
You can learn how to use a few other ListBox messages by browsing the source
code of the demonstration program provided on the companion CD.
1198
Appendix Windows API Functions
ComboBox Controls
As I explained in the previous section, ComboBox and ListBox controls supports some
common messages, even though the names and the values of the corresponding
symbolic constants are different. For example, you can read and modify the height
of items in the list portion using the CB_GETITEMHEIGHT and CB_SETITEMHEIGHT
messages, and you can search items using the CB_FINDSTRINGEXACT and CB_
FINDSTRING messages.
But the ComboBox control also supports other interesting messages. For example,
you can programmatically open and close the list portion of a drop-down ComboBox
control using the CB_SHOWDROPDOWN message:
‘ Open the list portion.
SendMessageByVal Combo1.hWnd, CB_SHOWDROPDOWN, True, 0
‘ Then close it.
SendMessageByVal Combo1.hWnd, CB_SHOWDROPDOWN, False, 0
and you can retrieve the current visibility state of the list portion using the CB_
GETDROPPEDSTATE message:
If SendMessageByVal(Combo1.hWnd, CB_GETDROPPEDSTATE, 0, 0) Then
‘ The list portion is visible.
End If
(See Figure A-3 for an example of a ComboBox whose drop-down list is wider
than usual.)
Finally, you can use the CB_LIMITTEXT message to set a maximum number of
characters for the control; this is similar to the MaxLength property for TextBox con-
trols, which is missing in ComboBox controls:
‘ Set the maximum length of text in a ComboBox control to 20 characters.
SendMessageByVal Combo1.hWnd, CB_LIMITTEXT, 20, 0
SYSTEM FUNCTIONS
Many internal Windows values and parameters are beyond Visual Basic’s capabili-
ties, but they’re just an API function call away. In this section, I show how you can
retrieve some important system settings and how you can augment Visual Basic
support for the mouse and the keyboard.
1199
Appendix
If you need to determine the actual Windows version, you need the
GetVersionEx API function, which returns information about the running operating
system in a UDT:
Type OSVERSIONINFO
dwOSVersionInfoSize As Long
dwMajorVersion As Long
dwMinorVersion As Long
dwBuildNumber As Long
dwPlatformId As Long
szCSDVersion As String * 128
End Type
Windows 95 returns a version number 4.00, and Windows 98 returns version 4.10.
(See Figure A-4.) You can use the build number to identify different service packs.
All tips and tricks collections show how you can retrieve the path to the main
Windows and System directories, which are often useful for locating other files that
might interest you. These functions are helpful for another reason as well: They show
you how to receive strings from an API function. In general, no API function directly
1200
Appendix Windows API Functions
returns a string; instead, all the functions that return a string value to the calling
program require that you create a receiving string buffer—typically, a string filled with
spaces or null characters—and you pass it to the routine. Most of the time, you must
pass the buffer’s length in another argument so that the API function doesn’t acci-
dentally write in the buffer more characters than allowed. For example, this is the
declaration of the GetWindowsDirectory API function:
Private Declare Function GetWindowsDirectory Lib “kernel32” Alias _
“GetWindowsDirectoryA” (ByVal lpBuffer As String, _
ByVal nSize As Long) As Long
Figure A-4. The sample program demonstrates several system, keyboard, and mouse
API functions.
You use this function by allocating a large-enough buffer, and then you pass it
to the function. The return value of the function is the actual number of characters
in the result string, and you can use this value to trim off characters in excess:
Dim buffer As String, length As Integer
buffer = Space$(512)
length = GetWindowsDirectory(buffer, Len(buffer))
Print “Windows Directory = “ & Left$(buffer, length)
You can use the same method to determine the path of the Windows\System
directory, using the GetSystemDirectory API function:
Private Declare Function GetSystemDirectory Lib “kernel32” Alias _
“GetSystemDirectoryA” (ByVal lpBuffer As String, _
ByVal nSize As Long) As Long
1201
Appendix
The GetUserName function returns the name of the user currently logged in. At
first glance, this function appears to use the same syntax as the functions I’ve just
described. The documentation reveals, however, that it doesn’t return the length of
the result but just a zero value to indicate a failure or 1 to indicate the success of the
operation. In this situation, you must extract the result from the buffer by searching
for the Null character that all API functions append to result strings:
Private Declare Function GetUserName Lib “advapi32.dll” Alias _
“GetUserNameA” (ByVal lpBuffer As String, nSize As Long) As Long
The GetComputerName API function, which retrieves the name of the computer
that’s executing the program, uses yet another method: You must pass the length of
the buffer in a ByRef argument. On exit from the function, this argument holds the
length of the result:
Private Declare Function GetComputerName Lib “kernel32” Alias _
“GetComputerNameA” (ByVal lpBuffer As String, nSize As Long) As Long
The Keyboard
Visual Basic’s keyboard events let you know exactly which keys are pressed and
when. At times, however, it’s useful to determine whether a given key is pressed even
when you’re not inside a keyboard event procedure. The pure Visual Basic solution
1202
Appendix Windows API Functions
is to store the value of the pressed key in a module-level or global variable, but it’s
a solution that negatively impacts the reusability of the code. Fortunately, you can
easily retrieve the current state of a given key using the GetAsyncKeyState function:
Private Declare Function GetAsyncKeyState Lib “user32” _
(ByVal vKey As Long) As Integer
This function accepts a virtual key code and returns an Integer value whose high-
order bit is set if the corresponding key is pressed. You can use all the Visual Basic
vbKeyxxxx symbolic constants as arguments to this function. For example, you can
determine whether any of the shift keys is being pressed using this code:
Dim msg As String
If GetAsyncKeyState(vbKeyShift) And &H8000 Then msg = msg & “SHIFT “
If GetAsyncKeyState(vbKeyControl) And &H8000 Then msg = msg & “CTRL “
If GetAsyncKeyState(vbKeyMenu) And &H8000 Then msg = msg & “ALT “
‘ lblKeyboard is a Label control that displays the shift key states.
lblKeyboard.Caption = msg
You can streamline your code by taking advantage of the following reusable
routine, which can test the state of up to three keys:
Function KeysPressed(KeyCode1 As KeyCodeConstants, Optional KeyCode2 As _
KeyCodeConstants, Optional KeyCode3 As KeyCodeConstants) As Boolean
If GetAsyncKeyState(KeyCode1) >= 0 Then Exit Function
If KeyCode2 = 0 Then KeysPressed = True: Exit Function
If GetAsyncKeyState(KeyCode2) >= 0 Then Exit Function
If KeyCode3 = 0 Then KeysPressed = True: Exit Function
If GetAsyncKeyState(KeyCode3) >= 0 Then Exit Function
KeysPressed = True
End Function
1203
Appendix
You can also modify the current state of a key, say, to programmatically change
the state of the CapsLock, NumLock, and ScrollLock keys. For an example of this
technique, see the “Toggling the State of Lock Keys” section in Chapter 10.
The Mouse
The support Visual Basic offers to mouse programming is defective in a few areas.
As is true for the keyboard and its event procedures, you can derive a few bits of
information about the mouse’s position and the state of its buttons only inside a
MouseDown, MouseUp, or MouseMove event procedure, which makes the creation of
reusable routines in BAS modules a difficult task. Even more annoying, mouse events
are raised only for the control under the mouse cursor, which forces you to write a
lot of code just to find out where the mouse is in any given moment. Fortunately,
querying the mouse through an API function is really simple.
To begin with, you don’t need a special function to retrieve the state of mouse
buttons because you can use the GetAsyncKeyState function with the special
vbKeyLButton, vbKeyRButton, and vbKeyMButton symbolic constants. Here’s a rou-
tine that returns the current state of mouse buttons in the same bit-coded format as
the Button parameter received by Mousexxxx event procedures:
Function MouseButton() As Integer
If GetAsyncKeyState(vbKeyLButton) < 0 Then
MouseButton = 1
End If
If GetAsyncKeyState(vbKeyRButton) < 0 Then
MouseButton = MouseButton Or 2
End If
If GetAsyncKeyState(vbKeyMButton) < 0 Then
MouseButton = MouseButton Or 4
End If
End Function
The Windows API includes a function for reading the position of the mouse
cursor:
Private Type POINTAPI
X As Long
Y As Long
End Type
1204
Appendix Windows API Functions
In both cases, the coordinates are in pixels and relative to the screen:
‘ Display current mouse screen coordinates in pixels using a Label control.
Dim lpPoint As POINTAPI
GetCursorPos lpPoint
lblMouseState = “X = “ & lpPoint.X & “ Y = “ & lpPoint.Y
The SetCursorPos API function lets you move the mouse cursor anywhere on
the screen, something that you can’t do with standard Visual Basic code:
Private Declare Function SetCursorPos Lib “user32” (ByVal X As Long, _
ByVal Y As Long) As Long
When you use this function, you often need to convert from client coordinates
to screen coordinates, which you do with the ClientToScreen API function. The fol-
lowing code snippet moves the mouse cursor to the center of a push button:
Private Declare Function ClientToScreen Lib “user32” (ByVal hWnd As Long, _
lpPoint As POINTAPI) As Long
‘ Get the coordinates (in pixels) of the center of the Command1 button.
‘ The coordinates are relative to the button’s client area.
Dim lpPoint As POINTAPI
lpPoint.X = ScaleX(Command1.Width / 2, vbTwips, vbPixels)
lpPoint.Y = ScaleY(Command1.Height / 2, vbTwips, vbPixels)
‘ Convert to screen coordinates.
ClientToScreen Command1.hWnd, lpPoint
‘ Move the mouse cursor to that point.
SetCursorPos lpPoint.X, lpPoint.Y
1205
Appendix
you can do by retrieving the window’s client area rectangle with the GetClientRect
API function and convert the result to screen coordinates. The following routine does
everything for you:
Private Declare Function ClipCursor Lib “user32” (lpRect As Any) As Long
Here’s an example that uses the previous routine and then cancels the clip-
ping effect:
‘ Clip the mouse cursor to the current form’s client area.
ClipMouseToWindow Me.hWnd
...
‘ When you don’t need the clipping any longer. (Don’t forget this!)
ClipCursor ByVal 0&
1206
Appendix Windows API Functions
A better approach would be to capture the mouse when the cursor enters the
control’s client area, using the SetCapture API function. When a form or a control
captures the mouse, it receives mouse messages until the user clicks outside the
form or the control or until the mouse capture is explicitly relinquished through a
ReleaseCapture API function. This technique permits you to solve the problem by
writing code in one single procedure:
‘ Add these declarations to a BAS module.
Private Declare Function SetCapture Lib “user32” (ByVal hWnd As Long) _
As Long
Private Declare Function ReleaseCapture Lib “user32” () As Long
Private Declare Function GetCapture Lib “user32” () As Long
‘ Change the BackColor of Frame1 control to yellow when the mouse enters
‘ the control’s client area, and restore it when the mouse leaves it.
Private Sub Frame1_MouseMove(Button As Integer, Shift As Integer, _
X As Single, Y As Single)
‘ Set the mouse capture unless the control already has it.
‘ (The GetCapture API function returns the handle of the window that
‘ has the mouse capture.)
If GetCapture <> Frame1.hWnd Then
SetCapture Frame1.hWnd
Frame1.BackColor = vbYellow
ElseIf X < 0 Or Y < 0 Or X > Frame1.Width Or Y > Frame1.Height Then
‘ If the mouse cursor is outside the Frame’s client area, release
‘ the mouse capture and restore the BackColor property.
ReleaseCapture
Frame1.BackColor = vbButtonFace
End If
End Sub
You can see this technique in action in the demonstration program shown in
Figure A-4. Anytime the user moves the mouse onto or away from the topmost Frame
control, the control’s background color changes.
The WindowsFromPoint API function often comes in handy when you’re work-
ing with the mouse because it returns the handle of the window at given screen
coordinates:
Private Declare Function WindowFromPointAPI Lib “user32” Alias _
“WindowFromPoint” (ByVal xPoint As Long, ByVal yPoint As Long) As Long
This routine returns the handle of the window under the mouse cursor:
Function WindowFromMouse() As Long
Dim lpPoint As POINTAPI
GetCursorPos lpPoint
WindowFromMouse = WindowFromPoint(lpPoint.X, lpPoint.Y)
End Function
1207
Appendix
For example, you can quickly determine from within a form module which con-
trol is under the mouse cursor using the following approach:
Dim handle As Long, ctrl As Control
On Error Resume Next
handle = WindowFromMouse()
For Each ctrl In Me.Controls
If ctrl.hWnd <> handle Then
‘ Not on this control, or hWnd property isn’t supported.
Else
‘ For simplicity’s sake, this routine doesn’t account for elements
‘ of control arrays.
Print “Mouse is over control “ & ctrl.Name
Exit For
End If
Next
For more information, see the source code of the demonstration application on
the companion CD.
These four commands can’t read and write to an arbitrary area in the Registry
but are limited to the HKEY_CURRENT_USER\Software\VB and VBA Program Settings
subtree of the Registry. For example, you can use the SaveSetting function to store the
initial position and size of the main form in the MyInvoicePrg application:
SaveSetting “MyInvoicePrg", “frmMain", “Left", frmMain.Left
SaveSetting “MyInvoicePrg", “frmMain", “Top", frmMain.Top
1208
Appendix Windows API Functions
You can see the result of this sequence of statements in Figure A-5.
Figure A-5. All Visual Basic Registry functions read and write values in the
HKEY_CURRENT_USER\Software\VB and VBA Program Settings subtree.
You can then read back these settings using the GetSetting function:
‘ Use the Move method to avoid multiple Resize and Paint events.
frmMain.Move GetSetting(“MyInvoicePrg", “frmMain", “Left", “1000”), _
GetSetting(“MyInvoicePrg", “frmMain", “Top", “800”), _
GetSetting(“MyInvoicePrg", “frmMain", “Width", “5000”), _
GetSetting(“MyInvoicePrg", “frmMain", “Height", “4000”)
If the specified key doesn’t exist, the GetSetting function either returns the values
passed to the Default argument or it returns an empty string if that argument is omitted.
GetAllSettings returns a two-dimensional array, which contains all the keys and val-
ues under a given section:
Dim values As Variant, i As Long
values = GetAllSettings(“MyInvoicePrg", “frmMain”)
‘ Each row holds two items, the key name and the key value.
For i = 0 To UBound(settings)
Print “Key =“ & values(i, 0) & “ Value = “ & values(i, 1)
Next
1209
Appendix
The last function of the group, DeleteSetting, can delete an individual key, or it
can delete all the keys under a given section if you omit its last argument:
The demonstration program shown in Figure A-6 demonstrates how you can
use the Visual Basic built-in Registry functions to save and to restore form settings.
Figure A-6. The demonstration program contains reusable routines for saving and
restoring form settings to the Registry.
Predefined keys
Before starting to play with API functions, you must have a broad idea of how the
Registry is arranged. The system Registry is a hierarchical structure that consists of
keys, subkeys, and values. More precisely, the Registry has a number of predefined
top-level keys, which I’ve summarized in Table A-1.
1210
Appendix Windows API Functions
1211
Appendix
hKey is the handle of an open key and can be one of the values listed in
Table A-1 or the handle of a key that you’ve opened previously. lpSubKey is the path
from the hKey key to the key that you want to open. ulOptions is a reserved argu-
ment and must be 0. samDesired is the type of access you want for the key that you
want to open and is a symbolic constant, such as KEY_READ, KEY_WRITE, or
KEY_ALL_ACCESS. Finally, phkResult is a Long variable passed by reference, which
receives the handle of the key opened by the function if the operation is successful.
You can test the success of the open operation by looking at the return value of the
RegOpenKeyEx function: A zero value means that the operation succeeded, and any
non-zero value is an error code. This behavior is common to all the Registry API
functions, so you can easily set up a function that tests the success state of any call.
(See the MSDN documentation for the list of error codes.)
As I mentioned earlier, you must close any open key as soon as you don’t need
it any longer, which you do with the RegCloseKey API function. This function takes
the handle of the key to be closed as its only argument, and returns 0 if the opera-
tion is successful:
Declare Function RegCloseKey Lib “advapi32.dll” (ByVal hKey As Long) _
As Long
so you can test the presence of the coprocessor using this routine:
‘ Assumes that all symbolic constants are correctly declared elsewhere.
Function MathProcessor() As Boolean
Dim hKey As Long, Key As String
Key = “HARDWARE\DESCRIPTION\System\FloatingPointProcessor"
If RegOpenKeyEx(HKEY_LOCAL_MACHINE, Key, 0, KEY_READ, hKey) = 0 Then
1212
Appendix Windows API Functions
As you might expect, the Registry API includes a function for creating new keys,
but its syntax is overly complex:
Declare Function RegCreateKeyEx Lib “advapi32.dll” Alias “RegCreateKeyExA"_
(ByVal hKey As Long, ByVal lpSubKey As String, ByVal Reserved As Long,_
ByVal lpClass As Long, ByVal dwOptions As Long, _
ByVal samDesired As Long, ByVal lpSecurityAttributes As Long, _
phkResult As Long, lpdwDisposition As Long) As Long
Most of the arguments have the same names and syntax as those that I’ve already
described for the RegOpenKeyEx function, and I won’t describe most of the new
arguments because they constitute a topic too advanced for this context. You can pass
a Long variable to the lpdwDisposition argument, and when the function returns you
can test the contents in this variable. The value REG_CREATED_NEW_KEY (1) means
that the key didn’t exist and has been created and opened by this function, whereas
the value REG_OPENED_EXISTING_KEY (2) means that the key already existed and
the function just opened it without altering the Registry in any way. To reduce the
confusion, I use the following routine, which creates a key if necessary and returns
True if the key already existed:
Function CreateRegistryKey(ByVal hKey As Long, ByVal KeyName As String) _
As Boolean
Dim handle As Long, disp As Long
If RegCreateKeyEx(hKey, KeyName, 0, 0, 0, 0, 0, handle, disp) Then
Err.Raise 1001, , “Unable to create the Registry key"
Else
‘ Return True if the key already existed.
If disp = REG_OPENED_EXISTING_KEY Then CreateRegistryKey = True
‘ Close the key.
RegCloseKey handle
End If
End Function
The following code snippet shows how you can use the CreateRegistryKey
function to create a key with the name of your company under the key HKEY_
CURRENT_USER\Software, which contains another key with the name of your
application. This is the approach followed by most commercial applications, includ-
ing all those by Microsoft and other leading software companies:
CreateRegistryKey HKEY_CURRENT_USER, “Software\YourCompany"
CreateRegistryKey HKEY_CURRENT_USER, “Software\YourCompany\YourApplication”
1213
Appendix
NOTE The CreateRegistryKey function, like all other Registry routines provided
on the companion CD, always closes a key before exiting. This approach makes
them “safe,” but it also imposes a slight performance penalty because each call
opens and closes a key that you might have to reopen immediately afterwards,
as in the preceding example. You can’t always have it all.
Finally, you can delete a key from the Registry, using the RegDeleteKey API
function:
Declare Function RegDeleteKey Lib “advapi32.dll” Alias “RegDeleteKeyA” _
(ByVal hKey As Long, ByVal lpSubKey As String) As Long
Under Windows 95 and 98, this function deletes a key and all its subkeys,
whereas under Windows NT you get an error if the key being deleted contains other
keys. For this reason, you should manually delete all the subkeys first:
‘ Delete the keys created in the previous example.
RegDeleteKey HKEY_CURRENT_USER, “Software\YourCompany\YourApplication"
RegDeleteKey HKEY_CURRENT_USER, “Software\YourCompany”
hKey is the handle of the open key that contains the value. lpValueName is the
name of the value you want to read. (Use an empty string for the default value.)
lpReserved must be zero. lpType is the type of the key. lpData is a pointer to a buffer
that will receive the data. lpcbData is a Long variable passed by reference; on entry
it has to contain the size in bytes of the buffer, and on exit it contains the number of
bytes actually stored in the buffer. Most Registry values you’ll want to read are of type
REG_DWORD (a Long value), REG_SZ (a null-terminated string), or REG_BINARY
(array of bytes).
The Visual Basic environment stores some of its configuration settings as values
under the following key:
HKEY_CURRENT_USER\Software\Microsoft\VBA\Microsoft Visual Basic
You can read the FontHeight value to retrieve the size of the font used for the
code editor, whereas the FontFace value holds the name of the font. Because the former
value is a Long number and the latter is a string, you need two different coding tech-
niques for them. Reading a Long value is simpler because you just pass a Long vari-
1214
Appendix Windows API Functions
able by reference to lpData and pass its length in bytes (which is 4 bytes) in lpcbData.
To retrieve a string value, on the other hand, you must prepare a buffer and pass it
by value, and when the function returns you must strip the excess characters:
Dim KeyName As String, handle As Long
Dim FontHeight As Long, FontFace As String, FontFaceLen As Long
Because you need to read Registry values often, I’ve prepared a reusable func-
tion that performs all the necessary operations and returns the value in a Variant. You
can also specify a default value, which you can use if the specified key or value doesn’t
exist. This tactic is similar to what you do with the Visual Basic intrinsic GetSetting
function.
Function GetRegistryValue(ByVal hKey As Long, ByVal KeyName As String, _
ByVal ValueName As String, ByVal KeyType As Integer, _
Optional DefaultValue As Variant = Empty) As Variant
1215
Appendix
To create a new Registry value or to modify the data of an existing value, you
use the RegSetValueEx API function:
Declare Function RegSetValueEx Lib “advapi32.dll” Alias “RegSetValueExA” _
(ByVal hKey As Long, ByVal lpValueName As String, _
ByVal Reserved As Long, ByVal dwType As Long, lpData As Any, _
ByVal cbData As Long) As Long
Let’s see how we can add a LastLogin value in the key HKEY_CURRENT_
USER\Software\YourCompany\YourApplication, that we created in the previous
section:
Dim handle As Long, strValue As String
‘ Open the key, check whether any error occurred.
If RegOpenKeyEx(HKEY_CURRENT_USER, “Software\YourCompany\YourApplication",_
0, KEY_WRITE, handle) Then
MsgBox “Unable to open the key."
Else
‘ We want to add a “LastLogin” value of type string.
strValue = FormatDateTime(Now)
‘ Strings must be passed using ByVal.
RegSetValueEx handle, “LastLogin", 0, REG_SZ, ByVal strValue, _
1216
Appendix Windows API Functions
Len(strValue)
‘ Don’t forget to close the key.
RegCloseKey handle
End If
On the companion CD, you’ll find the source code of the SetRegistryValue func-
tion, which automatically uses the correct syntax according to the type of value you’re
creating. Finally, by using the RegDeleteValue API function, you can delete a value
under a key that you opened previously:
Declare Function RegDeleteValue Lib “advapi32.dll” Alias “RegDeleteValueA"_
(ByVal hKey As Long, ByVal lpValueName As String) As Long
You must pass the handle of an open Registry key in the hKey argument, and
then you repeatedly call this function, passing increasing index values in dwIndex.
The lpName argument must be a string buffer of at least 260 characters (the maxi-
mum length for a key name), and lpcbName is the length of the buffer. When you
exit the routine, the buffer contains a Null-terminated string, so you have to strip all
the excess characters. To simplify your job, I’ve prepared a function that iterates on
all the subkeys of a given key and returns a String array that contains the names of
all the subkeys:
Function EnumRegistryKeys(ByVal hKey As Long, ByVal KeyName As String) _
As String()
Dim handle As Long, index As Long, length As Long
ReDim result(0 To 100) As String
1217
Appendix
End If
length = 260 ‘ Max length for a key name.
result(index) = Space$(length)
If RegEnumKey(hKey, index, result(index), length) Then Exit For
‘ Trim excess characters.
result(index) = Left$(result(index), InStr(result(index), _
vbNullChar) - 1)
Next
Figure A-7. You can use Registry API routines to list all the components installed on
your machine, with their CLSIDs and the locations of their executable files.
1218
Appendix Windows API Functions
The Windows API also exposes a function for enumerating all the values under
a given open key:
Declare Function RegEnumValue Lib “advapi32.dll” Alias “RegEnumValueA” _
(ByVal hKey As Long, ByVal dwIndex As Long, ByVal lpValueName As _
String, lpcbValueName As Long, ByVal lpReserved As Long, _
lpType As Long, lpData As Any, lpcbData As Long) As Long
This function returns the type of each value in the lpType variable and the
contents of the value in lpData. The difficulty is that you don’t know in advance what
the type of the value is, and therefore you don’t know the kind of variable—Long,
String, or Byte array—you should pass in lpData. The solution to this problem is to
pass a Byte array and then move the result into a Long variable using the CopyMemory
API routine or into a String variable using the VBA StrConv function. On the com-
panion CD, you’ll find the complete source of the EnumRegistryValues routine, which
encapsulates all these details and returns a two-dimensional array of Variants con-
taining all the values’ names and data. For example, you can use this routine to retrieve
all the Microsoft Visual Basic configuration values:
Dim values() As Variant, i As Long
values() = EnumRegistryValues(HKEY_CURRENT_USER, _
“Software\Microsoft\VBA\Microsoft Visual Basic”)
For i = LBound(values, 2) To UBound(values, 2)
‘ Row 0 holds the value’s name, row 1 holds its value.
List1.AddItem values(0, i) & “ = “ & values(1, i)
Next
Callback Techniques
Callback and subclassing capabilities are relatively new to Visual Basic in that they
weren’t possible until version 5. What made these techniques available to Visual Basic
programmers was the introduction of the new AddressOf keyword under Visual Basic 5.
This keyword can be used as a prefix for the name of a routine defined in a BAS module,
and evaluates to the 32-bit address of the first statement of that routine.
1219
Appendix
System timers
To show this keyword in action, I’ll show you how you can create a timer without a
Timer control. Such a timer might be useful, for example, when you want to peri-
odically execute a piece of code located in a BAS module, and you don’t want to add
a form to the application just to get a pulse at regular intervals. Setting up a system
timer requires only a couple of API functions:
Declare Function SetTimer Lib “user32” (ByVal hWnd As Long, ByVal nIDEvent_
As Long, ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long
For our purposes, we can ignore the first two arguments to the SetTimer func-
tion and just pass the uElapse value (which corresponds to the Interval property of
a Timer control) and the lpTimerFunc value (which is the address of a routine in our
Visual Basic program). This routine is known as the callback procedure because it’s
meant to be called from Windows and not from the code in our application. The
SetTimer function returns the ID of the timer being created or 0 in case of error:
Dim timerID As Long
‘ Create a timer that sends a notification every 500 milliseconds.
timerID = SetTimer(0, 0, 500, AddressOf Timer_CBK)
You need the return value when it’s time to destroy the timer, a step that you
absolutely must perform before closing the application if you don’t want the program
to crash:
‘ Destroy the timer created previously.
KillTimer 0, timerID
Let’s see now how to build the Timer_CBK callback procedure. You derive the
number and types of the arguments that Windows sends to it from the Windows SDK
documentation or from MSDN:
Sub Timer_CBK(ByVal hWnd As Long, ByVal uMsg As Long, _
ByVal idEvent As Long, ByVal SysTime As Long)
‘ Just display the system time in a label control.
Form1.lblTimer = SysTime
End Sub
In this implementation, you can safely ignore the first three parameters and
concentrate on the last one, which receives the number of milliseconds elapsed since
the system started. This particular callback routine doesn’t return a value and is there-
fore implemented as a procedure; you’ll see later that in most cases callback routines
return values to the operating system and therefore are implemented as functions.
As usual, you’ll find on the companion CD a complete demonstration program that
contains all the routines described in this section.
1220
Appendix Windows API Functions
Windows enumeration
Interesting and useful examples of using callback techniques are provided by the
EnumWindows and EnumChildWindows API functions, which enumerate the top-
level windows and the child windows of a given window, respectively. The approach
used by these functions is typical of most API functions that enumerate Windows
objects. Instead of loading the list of windows in an array or another structure, these
functions use a callback procedure in the main application for each window found.
Inside the callback function, you can do what you want with such data, including
loading it into an array or into a ListBox or TreeView control. The syntax for these
functions is the following:
Declare Function EnumWindows Lib “user32” (ByVal lpEnumFunc As Long, _
ByVal lParam As Long) As Long
where hWnd is the handle of the window found, and lParam is the value passed as
the last argument to the EnumWindows or EnumChildWindows function. This func-
tion returns 1 to ask the operating system to continue the enumeration or 0 to stop
the enumeration.
It’s easy to create a reusable procedure that builds on these API functions and
returns an array with the handles of all the child windows of a given window:
‘ An array of Longs holding the handles of all child windows
Dim windows() As Long
‘ The number of elements in the array.
Dim windowsCount As Long
‘ Return an array of Longs holding the handles of all the child windows
‘ of a given window. If hWnd = 0, return the top-level windows.
Function ChildWindows(ByVal hWnd As Long) As Long()
windowsCount = 0 ‘ Reset the result array.
If hWnd Then
EnumChildWindows hWnd, AddressOf EnumWindows_CBK, 1
Else
EnumWindows AddressOf EnumWindows_CBK, 1
End If
(continued)
1221
Appendix
1222
Appendix Windows API Functions
Figure A-8. A utility to explore all the open windows in the system.
Subclassing Techniques
Now that you know what a callback procedure is, comprehending how subclassing
works will be a relatively easy job.
Basic subclassing
You already know that Windows communicates with applications via messages, but
you don’t know yet how the mechanism actually works at a lower level. Each window
is associated with a window default procedure, which is called any time a message
is sent to the window. If this procedure were written in Visual Basic, it would look
like this:
Function WndProc(ByVal hWnd As Long, ByVal uMsg As Long, _
ByVal wParam As Long, ByVal lParam As Long) As Long
...
End Function
The four parameters that a window procedure receives are exactly the arguments
that you (or the operating system) pass to SendMessage when you send a message to
a given window. The purpose of the window procedure is to process all the incom-
ing messages and react appropriately. Each class of windows—top-level windows,
MDI windows, TextBox controls, ListBox controls, and so on—behave differently
because their window procedures are different.
The principle of the subclassing technique is simple: You write a custom window
procedure, and you ask Windows to call your window procedure instead of the
standard window procedure associated with a given window. The code in your
1223
Appendix
Visual Basic application traps all the messages sent to the window before the win-
dow itself (more precisely, its default window procedure) has a chance to process
them, as I explain in the following illustration:
1. Windows sends
a message to a 2. Your subclassing code
Windows
Visual Basic form. intercepts all the incoming
messages and processes them.
Sub WndProc(...)
If uMsg = WM_MOVE Then
‘ Process the message.
End If
WndProc = CallWindowProc (...)
End Sub
hWnd is the handle of the window. ndx is the index of the slot in the internal
data table where you want to store the value. And newValue is the 32-bit value to
be stored in the internal data table at the position pointed to by nxd. This function
returns the value that was previously stored in that slot of the table; you must store
such a value in a variable because you must definitely restore it before the applica-
tion terminates or the subclassed window is closed. If you don’t restore the address
of the original window procedure, you’re likely to get a GPF. In summary, this is the
minimal code that subclasses a window:
Dim saveHWnd As Long ‘ The handle of the subclassed window
Dim oldProcAddr As Long ‘ The address of the original window procedure
1224
Appendix Windows API Functions
Sub StopSubclassing()
SetWindowLong saveHWnd, GWL_WNDPROC, oldProcAddr
End Sub
Let’s focus on what the custom window procedure actually does. This procedure
can’t just process a few messages and forget about the others. On the contrary, it’s
responsible for correctly forwarding all the messages to the original window proce-
dure; otherwise, the window wouldn’t receive all the vital messages that inform it
when it has to resize, close, or repaint itself. In other words, if the window procedure
stops all messages from reaching the original window procedure, the application won’t
work as expected any longer. The API function that does the message forwarding is
CallWindowProc:
Declare Function CallWindowProc Lib “user32” Alias “CallWindowProcA” _
(ByVal lpPrevWndFunc As Long, ByVal hwnd As Long, ByVal Msg As Long, _
ByVal wParam As Long, ByVal lParam As Long) As Long
1225
Appendix
Figure A-9. A program that demonstrates the basic concepts of window subclassing.
You can generally process the incoming messages before or after calling the
CallWindowProc API function. If you’re interested only in knowing when a message
is sent to the window, it’s often preferable to trap it after the Visual Basic runtime
has processed it because you can query updated form’s properties. Remember, Win-
dows expects that you return a value to it, and the best way to comply with this
requirement is by using the value returned by the original window procedure. If you
process a message before forwarding it to the original procedure, you can change
the values in wParam or lParam, but this technique requires an in-depth knowledge
of the inner workings of Windows. Any error in this phase is fatal because it prevents
the Visual Basic application from working correctly.
CAUTION Of all the advanced programming techniques you can employ in
Visual Basic, subclassing is undoubtedly the most dangerous one. If you make
a mistake in the custom window procedure, Windows won’t forgive you and won’t
give you a chance to fix the error. For this reason, you should always save your
code before running the program in the environment. Moreover, you should never
stop a running program using the End button, an action which immediately
stops the running program and prevents the Unload and Terminate events from
executing, therefore depriving you of the opportunity to restore the original win-
dow procedure.
1226
Appendix Windows API Functions
■ You can’t use simple variables to store the window’s handle and the
address of the original window procedure—as the previous simplified
example does—but you need an array or a collection to account for
multiple windows.
■ The custom window procedure must reside in a BAS form, so the same
procedure must serve multiple subclassed windows and you need a way
to understand which window each message is bound to.
The best solution to both problems is to build a class module that manages all
the subclassing chores in the program. I’ve prepared such a class, named MsgHook,
and as usual you’ll find it on the companion CD. Here’s an abridged version of its
source code:
‘ The MsgHook.cls class module
Event AfterMessage(ByVal hWnd As Long, ByVal uMsg As Long, _
ByVal wParam As Long, ByVal lParam As Long, retValue As Long)
1227
Appendix
As you see, the class communicates with its clients through the AfterMessage
event, which is called immediately after the original window procedure has processed
the message. From the client application’s standpoint, subclassing a window has be-
come just a matter of responding to an event, an action familiar to all Visual Basic
programmers.
Now analyze the code in the BAS module in which the subclassing actually
occurs. First of all, you need an array of UDTs, where you can store information about
each window being subclassed:
‘ The WndProc.Bas module
Type WindowInfoUDT
hWnd As Long ‘ Handle of the window being subclassed
oldWndProc As Long ‘ Address of the original window procedure
obj As MsgHook ‘ The MsgHook object serving this window
End Type
‘ Store data in the array, and start the subclassing of this window.
With WindowInfo(WindowInfoCount)
.hWnd = hWnd
Set .obj = obj
.oldWndProc = SetWindowLong(hWnd, GWL_WNDPROC, AddressOf WndProc)
1228
Appendix Windows API Functions
End With
End Sub
The last procedure left to be seen in the BAS module is the custom window
procedure. This procedure has to search for the handle of the target window of the
incoming message among those stored in the WindowInfo array and notify the corre-
sponding instance of the MsgHook class that a message has arrived:
‘ The custom window procedure
Function WndProc(ByVal hWnd As Long, ByVal uMsg As Long, _
ByVal wParam As Long, ByVal lParam As Long) As Long
Dim i As Long, obj As MsgHook
Const WM_DESTROY = &H2
NOTE The preceding code looks for the window handle in the array using a
simple linear search; when the array contains only a few items, this approach is
sufficiently fast and doesn’t add significant overhead to the class. If you plan to
subclass more than a dozen forms and controls, you should implement a more
sophisticated search algorithm, such as a binary search or a hash table.
1229
Appendix
In general, a window is subclassed until the client application calls the StopSubclass
method of the related MsgHook object or until the object itself goes out of scope.
(See the code in the class’s Terminate event procedure.) The code in the WndProc
procedure uses an additional trick to ensure that the original window procedure is
restored before the window is closed. Because it’s already subclassing the window,
it can trap the WM_DESTROY message, which is the last message (or at least one of
the last messages) sent to a window before it closes. When this message is detected,
the code immediately stops subclassing the window.
If you want to subclass other forms or controls, you have to create multiple
instances of the MsgHook class—one for each window to be subclassed—and assign
them to distinct WithEvents variables. And of course, you have to write the proper
code in each AfterMessage event procedure. The complete class provided on the com-
panion CD supports some additional features, including a BeforeMessage event that
fires before the original window procedure processes the message and an Enabled
property that lets you temporarily disable the subclassing for a given window. Keep
in mind that the MsgHook class can subclass only windows belonging to the current
application; interprocess window subclassing is beyond the current capabilities of
Visual Basic and requires some C/C++ wizardry.
The MsgHook class module encapsulates most of the dangerous details of the
subclassing technique. When you turn it into an ActiveX DLL component—or use the
version provided on the companion CD—you can safely subclass any window cre-
ated by the current application. You can even stop an interpreted program without
any adverse effects because the End button doesn’t prevent the Terminate event from
1230
Appendix Windows API Functions
firing if the class has been compiled in a separate component. The compiled version
also solves most—but not all—of the problems that occur when an interpreted code
enters break mode, during which the subclassing code can’t respond to messages. In
such situations, you usually get an application crash, but the MsgHook class will pre-
vent it from happening. I plan to release a more complete version of this class, which
I’ll make available for download from my Web site at http://www.vb2themax.com.
More subclassing examples
Now that you have a tool that implements all the nitty-gritty details of subclassing,
you might finally see how subclassing can actually help you deliver better applica-
tions. The examples I show in this section are meant to be just hints of what you can
really do with this powerful technique. As usual, you’ll find all the code explained
in this section in a sample application provided on the companion CD. The demon-
stration application is also shown in Figure A-10.
Figure A-10. The demonstration application that shows what you can achieve with
the MsgHook ActiveX DLL.
Windows sends Visual Basic forms a lot of messages that the Visual Basic
runtime doesn’t expose as events. Sometimes you don’t have to manipulate incoming
parameters because you’re subclassing the form only to find out when the message
arrives. There are many examples of such messages, including WM_MOUSEACTIVATE
(the form or control is being activated with the mouse), WM_TIMECHANGE (the
system date and time has changed), WM_DISPLAYCHANGE (the screen resolution
has changed), WM_COMPACTING (Windows is low in memory and is asking appli-
cations to release as much memory as possible), and WM_QUERYOPEN (a form is
about to be restored to normal size from an icon).
1231
Appendix
Many other messages can’t be dealt with so simply, though. For example, the
WM_GETMINMAXINFO message is sent to a window when the user begins to move
or resize it. When this message arrives, lParam contains the address of a MINMAXINFO
structure, which in turn holds information about the region to which the form can be
moved and the minimum and maximum size that the window can take. You can
retrieve and modify this data, thus effectively controlling a form’s size and position
when the user resizes or maximizes it. (If you carefully look at Figure A-10, you’ll
see from the buttons in the window’s caption that this form is maximized, even if it
doesn’t take the entire screen estate.) To move this information into a local structure,
you need the CopyMemory API function:
Type POINTAPI
X As Long
Y As Long
End Type
Type MINMAXINFO
ptReserved As POINTAPI
ptMaxSize As POINTAPI
ptMaxPosition As POINTAPI
ptMinTrackSize As POINTAPI
ptMaxTrackSize As POINTAPI
End Type
1232
Appendix Windows API Functions
1233
Appendix
This appendix has taken you on quite a long journey through API territory. But as I
told you at the beginning, these pages only scratch the surface of the immense power
that Windows API functions give you, especially if you couple them with subclassing
techniques. The MsgHook class on the companion CD is a great tool for exploring
these features because you don’t have to worry about the implementation details,
and you can concentrate on the code that produces the effects you’re interested in.
If you want to learn more about this subject, I suggest that you get a book, such
as Visual Basic Programmer’s Guide to the Win32 API by Dan Appleman, specifically
on this topic. You should also always have the Microsoft Developer Network at hand
for the official documentation of the thousands of functions that Windows exposes.
Become an expert in API programming, and you’ll see that there will be very little
that you can’t do in Visual Basic.
1234