Platform Invoke Examples

The following examples demonstrate how to define and call the MessageBox function in User32.dll, passing a simple string as an argument. In the examples, the DllImportAttribute.CharSet Field field is set to Auto to let the target platform determine the character width and string marshaling.

The same example appears in Visual Basic, C#, and C++. To show all examples, click the Language Filter button 42b9ea93.Filter2(en-us,VS.100).gif in the upper-left corner of the page. For additional examples, see Marshaling Data with Platform Invoke.

Imports System.Runtime.InteropServices

Public Class Win32
    Declare Auto Function MessageBox Lib "user32.dll" _
       (ByVal hWnd As Integer, ByVal txt As String, _
       ByVal caption As String, ByVal Typ As Integer) As IntPtr
End Class

Public Class HelloWorld    
    Public Shared Sub Main()
        Win32.MessageBox(0, "Hello World", "Platform Invoke Sample", 0)
    End Sub
End Class
using System.Runtime.InteropServices;

public class Win32 {
     [DllImport("user32.dll", CharSet=CharSet.Auto)]
     public static extern IntPtr MessageBox(int hWnd, String text, 
                     String caption, uint type);
}

public class HelloWorld {
    public static void Main() {
       Win32.MessageBox(0, "Hello World", "Platform Invoke Sample", 0);
    }
}      
using namespace System::Runtime::InteropServices;

typedef void* HWND;
[DllImport("user32", CharSet=CharSet::Auto)]
extern "C" IntPtr MessageBox(HWND hWnd,
                          String* pText,
                          String* pCaption,
                          unsigned int uType);
void main(void) {
     String* pText = L"Hello World!";
     String* pCaption = L"Platform Invoke Sample";
     MessageBox(0, pText, pCaption, 0);
}

See Also

Reference

DllImportAttribute

Concepts

Creating Prototypes in Managed Code

Specifying a Character Set