Determine whether an API function is available

Determine whether an API function is available

In many cases you may want to call an API function, but you aren’t sure whether the Windows version the application is running on supports that particular function.

The easiest way to test whether a function exists and can be called is to replicate through VB code what Windows itself would do when calling the function. First, you try to load the DLL module using the LoadLibrary API function, and then you call the GetProcAddress API to retrieve the actual address. If you get a non-zero address, then the function has been found.

I have enclosed all these details in the followed routine:

Private Declare Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal _    lpLibFileName As String) As LongPrivate Declare Function GetProcAddress Lib "kernel32" (ByVal hModule As Long, _    ByVal lpProcName As String) As LongPrivate Declare Function FreeLibrary Lib "kernel32" (ByVal hLibModule As Long) _    As LongFunction IsProcedureAvailable(ByVal ProcedureName As String, _    ByVal DllFilename As String) As Boolean    Dim hModule As Long, procAddr As Long    ' first, attempt to load the module    hModule = LoadLibrary(DllFilename)    If hModule Then        ' then, retrieve the address of the routine        procAddr = GetProcAddress(hModule, ProcedureName)        ' finally, decrement the DLL usage counter        FreeLibrary hModule    End If    ' if procAddr is non-zero, the function is available    IsProcedureAvailable = (procAddr <> 0)End Function

Here’s an example that shows how you can test whether the machine your app is running on does support the Support the “GetDiskFreeSpaceEx” API function (that was introduced in Windows 95 OSR2 release):

If IsProcedureAvailable("GetDiskFreeSpaceExA", "kernel32") Then    MsgBox "GetDiskFreeSpaceEx is supported"End If

Note that you can omit the “dll” extension in DllFileName, but you have to provide the complete path to the file if it isn’t in one of the system directories. Moreover, keep in mind that you should pass the real name of the procedure, not the alias used in VB. For example, most routines that accept strings among their arguments have a “A” and “W” version – for ANSI and Unicode strings, respectively – and you must include those trailing characters in the argument passed to IsProcedureAvailable.

See also  5 Tips for Choosing the Right Medical Software for Your Practice

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist