3 out of 4 rated this helpful - Rate this topic

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.90).gif in the upper-left corner of the page. For additional examples, see Marshaling Data with Platform Invoke.

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);
    }
}      

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
It works, but it's using System;, not using Systems;.
using System;
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);
    }
}
Example works
The example works correctly - you just have to add :

using systems;

...

Otherwise the string type is not known.

Incorrect sample

The example code seems to be incorrect (in all languages) since the first parameter of the MessageBox WinAPI function is a handle and returns an int value, so in C# it should read:

[DllImport("user32", CharSet=CharSet.Auto)]
public static extern int MessageBox(
IntPtr hWnd,
string lpText,
string lpCaption,
uint uType
);