| A
callback is a function you write and tell Windows to call for some reason.
You create your own function with a specified number and type of parameters,
then tell Windows that this function should be called for some reason and
its parameters filled with some info you need. Then Windows calls your
function, you handle the parameters and exit from the function returning
some kind of value.
A typical use
of callbacks is for receiving a continuous stream of data from Windows.
Here is the declaration of a function that requires a callback:
Declare
Function EnumWindows Lib "User32" (ByVal lpEnumFunc As Long, ByVal lParam
As Long) As Long
The first parameter
is the address of your callback function, and the second is a whatever
value you want. This value will be passed to your function, so that you
know what it is called for.
VB 5.0 has provided
a useful operator called AddressOf which returns
the address of a function (there is no such operator in VB 4.0). It may
be used only in front of a parameter when you call a function and uses
like
FuncP
= AddressOf MyFunction
are wrong and
cause error. So, you must call EnumWindows
like that:
Success&
= EnumWindows(AddressOf cbFunc, 58&)
You must also
write the callback function. There are different type of callbacks that
have a different sets of parameters. Description of this parameter can
be found in a SDK Help file or MS SDK documentation. Here is the declaration
for the callback:
Public
Function cbFunc (ByVal Hwnd As Long, ByVal lParam As Long) as Long
Here is a sample
of callbacks:
(paste this
code in a module, as callbacks should be Public)
Declare
Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd
As Long, ByVal lpString As String, ByVal cch As Long) As Long
Declare
Function EnumWindows Lib "User32" (ByVal lpEnumFunc As Long, ByVal lParam
As Long) As Long
Public
Function cbFunc(ByVal Hd As Long, ByVal lParam As Long) As Long
If
lParam = 58 Then 'enum windows
Dim
St As String
St
= Space(255)
Ret&
= GetWindowText(Hd, St, Len(St))
Debug.Print
Left(St, Ret&)
cbFunc
= 1
End
If
End
Function
(paste the following
in a form module with a command button on it)
Private
Sub Command1_Click()
Success&
= EnumWindows(AddressOf cbFunc, 58&)
End
Sub
Note that the
function returns 1. If it returns 0,
the enumeration will stop. Watch the Immediate Window.
This sample
enumerates the captions of all (literally) windows (no childs). |