Calling an API Function From VB.NET

This snippet calls the GetSystemDirectory API function in VB.NET and shows how to use the StringBuilder class to create a string buffer for API functions that require it. See comments within code for more information.

Put this at the top of your module.
'Required in all cases when calling API functions
Imports System.Runtime.InteropServices

'Required in this example and any API function which
'use a string buffer. Provides the StringBuilder class

Imports System.Text

'Put these declarations right under the class declaration
'(e.g., in a Form, right under Public Class Form1)

SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, _
CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function GetSystemDirectory(ByVal Buffer _
As StringBuilder, ByVal Size As Integer) As Long
' Leave function empty - DLLImport attribute
' forces calls to GetSystemDirectory to
' be forwarded to GetSystemDirectory in KERNEL32.DLL
End Function

Public Const MAX_PATH As Integer = 256

'How to call the API function:

Dim s As New StringBuilder(MAX_PATH)

GetSystemDirectory(s, MAX_PATH)
msgbox(s.ToString(), , "System Directory")


Post a Comment