Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VB4/32,VB5,VB6
Expertise: Intermediate
Aug 21, 1999

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 Long
Private Declare Function GetProcAddress Lib "kernel32" (ByVal hModule As Long, _
    ByVal lpProcName As String) As Long
Private Declare Function FreeLibrary Lib "kernel32" (ByVal hLibModule As Long) _
    As Long

Function 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.
Francesco Balena
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date