How to: Call Windows APIs (Visual Basic)


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017, see Visual Studio 2017 Documentation.

This example defines and calls the MessageBox function in user32.dll and then passes a string to it.

    ' Defines the MessageBox function.
    Public Class Win32
        Declare Auto Function MessageBox Lib "user32.dll" (
            ByVal hWnd As Integer, ByVal txt As String,
            ByVal caption As String, ByVal Type As Integer
            ) As Integer
    End Class

    ' Calls the MessageBox function.
    Public Class DemoMessageBox
        Public Shared Sub Main()
            Win32.MessageBox(0, "Here's a MessageBox", "Platform Invoke Sample", 0)
        End Sub
    End Class

This example requires:

  • A reference to the System namespace.

The following conditions may cause an exception:

A Closer Look at Platform Invoke
Platform Invoke Examples
Consuming Unmanaged DLL Functions
Defining a Method with Reflection Emit
Walkthrough: Calling Windows APIs
COM Interop