Codingdomain.com

A simple API call with Visual Basic

Introduction

This page shows a simple example about calling an API function.

Example code

The code below declares the Sleep() API in the current name space, and it can be used in the Visual Basic code.

A simple API call:
' Declare an API from kernel32.dll in the current name space
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Public Sub Main()
  MsgBox "After pressing OK, " _
       & "the next message will appear in 1500 milliseconds", _
         vbInformation

  Sleep 1500 ' This calls the sub declared above

  MsgBox "This is the next message", vbExclamation
End Sub

This is the most simple API you can use. But there is more you need to know about parameter declarations.

In the example above, note the ByVal statement. The ByVal statement causes Visual Basic to pass the variable value. If the ByVal keyword was omitted, Visual Basic would have used it's default ByRef behavour.

Just to let you know...
If you did omit the ByVal, Visual Basic would have passed the memory address of your variable. This value would be "454908432" for instance. It doesn't take much effort to realize that calling Sleep(454908432) makes your program not responding for a very long time.

blog comments powered by Disqus