ProcAddr Function

Purpose

Returns the memory address of a subroutine.

Syntax

a% = ProcAddr(procname)

a%: iexp
procname: proceedure name

Description

With the function ProcAddr() you determine the address of a Sub, Procedure, Function, or FunctionVar. The return is an Integer value.

ProcAddr permits the address of the procedure to be passed to a Windows API function in a dynamic-link library (DLL), rather passing the procedure's return value. The API function can then use the address to call the Basic procedure, a process known as a callback.

For example, the EnumWindows function from the Win32 API (built-in)

Function EnumWindows(lpEnumFunc as Long, lParam as Long ) As Long

EnumWindows is an enumeration function, which means that it can list the handle of every open window on your system. EnumWindows works by repeatedly calling the function you pass to its first argument (lpEnumFunc). Each time EnumWindows calls the function, EnumWindows passes it the handle of an open window.

When you call EnumWindows from your code, you pass a user-defined function to this first argument to handle the stream of values. For example, you might write a function to add the values to a list box, convert the hWnd values to window names, or take whatever action you choose.

To specify that you're passing a user-defined function as an argument, you first obtain the address of the function with the ProcAddr, and then pass that address to the first parameter of EnumWindows. Any suitable value can be passed to the second argument. The user-defined function you specify when you call the procedure is referred to as the callback function. Callback functions (or "callbacks," as they are commonly called) can perform any action you specify with the data supplied by the procedure. See example.

A callback function must have a specific set of arguments, as determined by the API from which the callback is referenced. Refer to your API documentation for information on the necessary arguments and how to call them.

In the same way the ProcAddr function can be used to obtain the address of a window function when registering a window class. Hook function can be implemented as anything that requires a function pointer.

Example

OpenW 1, , , 300, 300

Ocx ListBox lb = , 10, 10, 280, 200

Dim cnt%

Trace EnumWindows(ProcAddr(EnumWndProc), V:cnt)

MsgBox "Window count: " & Dec(cnt)

Do

Sleep

Until Me Is Nothing

 

Function EnumWndProc(hWnd As Long, lParam As Long) As Long

' Increment count

{lParam} = {lParam} + 1

' Get window title and insert into ListBox

Dim s As String = _Win$(hWnd)

If Then

lb.AddItem s

lb.ItemData(lb.NewIndex) = hWnd

End If

EnumWndProc = True   '  keep enumerating

End Function

Remarks

You can use ProcAddr to call a function or procedure through such a pointer from within Basic using the StdCall(ProcAddr(subname))().

See Also

LabelAddr, DisAsm, StdCall

{Created by Sjouke Hamstra; Last updated: 17/05/2017 by James Gaite}