API Programming Series #2

The Code

First, load VB and create a new standard EXE project. A form should have been added to the project by default. In the General | Declarations section of the form's code window add the following code:

Private Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal sBuffer As String, lSize As Long) As Long

Now add the following code to an appropriate event handler/procedure. Here I've used the Form_Load event

Private Sub Form_Load ()
  Dim strString As String
  'Create a buffer
  strString = String(255, Chr$(0))
  'Get the computer name
  GetComputerName strString, 255
  'Remove the unnecessary Chr$(0)
  strString = Left$(strString, InStr(1, strString, Chr$(0)) - 1)
  'Show the computer name
  MsgBox strString
End Sub

Please examine the Declaration part carefully. Straightaway, we can notice several things. First of all we see that the scope of the Declaration is private. This is because VB does not allow Public Declare statements in object modules. Next we see that this is the declaration for a Function and that the name by which the function is referred in this program is GetComputerName. This is NOT the real name of the function as will become clear when we discuss aliasing in a short while.

The next two words are interesting. Lib "kernel32" means that the specified API function is found in the kernel32.dll file. Strictly speaking, it should be "kernel32.dll" but the extension name can be skipped. Also, the path can be skipped since the file is to be found in the System folder.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“It is practically impossible to teach good programming style to students that have had prior exposure to BASIC. As potential programmers, they are mentally mutilated beyond hope of regeneration.” - E. W. Dijkstra