Visual Basic/API Use
The Windows API is a rich set of functions for accomplishing common tasks. There are several thousand of these functions, and all are documented on Microsoft's website, MSDN.
Declaring API functions
[edit | edit source]API functions are stored in DLL files ("Dynamic Link Libraries"; Sometimes called libraries or libs). For your program to use functions from a library, they must first be declared. Declaring a function uses the following syntax:
Declare Function (function name) Lib (library) (arguments)
To declare a function, you must first know what library it is in, and then any arguments it accepts. Happily, these are very easy to discover, often by either going to the link above (MSDN) or googling.
Example
[edit | edit source]Here, we will use a simple function, called beep to demonstrate how to use API functions. First, we must declare it, the beep function is declared as follows:
Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long
Once a function is declared, it can be used as if it were a built-in function of Visual Basic. To use the beep function, you must provide a frequency (in hertz), and a duration (in milliseconds). The following line would beep for 1 second at 440 hertz:
Beep 440, 1000
Here's an example of something very strange you can do with Beep API + a For Loop:
Option Explicit Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long Private Sub Form_Paint() Dim i As Integer For i = 1 To 2600 DoEvents Beep i, 3 ' "Techno rain": Beep Rnd() * 20000, 5 ' "Life as a computer in hollywood": Beep Rnd() * 20000, 15 ' "YAY! I beat a game from the 70s!": Beep Rnd() * 2000, 20 ' "Scary part of a game from the 70s": Beep Rnd() * 2000, 200 Next i DoEvents Beep 200, 500 End Sub
Finding documentation on the functions
[edit | edit source]There are literally thousands of Windows API functions out there, and guessing the code to declare one is difficult. A list of all functions, their uses, and the code to declare them can be found at the following URL on Microsoft's website:
You can also find API functions from the AllAPI Network, which has a collection of every function and it's use in VB6 as well as VB.NET, along with examples and related functions. This website is also home to a VB6 extension called ApiViewer, which is a massive extension to the outdated program that comes with VB6.
Learning Visual Basic |
Previous: (none) — Next: (none) |