以下示例将说明如何定义和调用 User32.dll 中的 MessageBox 函数,并将简单字符串当作参数进行传递。在这些示例中,CharSet 对象字段设置为 Auto,以便让目标平台确定字符宽度和字符串封送处理。
[Visual Basic]
Imports System.Runtime.InteropServices
Public Class Win32
Declare Auto Function MessageBox Lib "user32.dll"(hWnd As Integer, _
txt As String, caption As String, Typ As Integer) As Integer
End Class
Public Class HelloWorld
Public Shared Sub Main()
Win32.MessageBox(0, "Hello World", "Platform Invoke Sample", 0)
End Sub
End Class
[C#]
using System.Runtime.InteropServices;
public class Win32 {
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern int 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);
}
}