Share via


平台叫用範例

更新:2007 年 11 月

下列範例說明如何定義和呼叫 User32.dll 中的 MessageBox 函式,將一個簡單字串做為引數傳遞。在這些範例中,DllImportAttribute.CharSet Field 欄位會設為 Auto,讓目標平台決定字元寬度和字串封送處理 (Marshaling)。

同樣的範例會出現在 Visual Basic、C# 和 C++ 中。若要顯示所有範例,請按一下頁面左上角的 [語言篩選條件] 按鈕。若需額外的範例,請參閱使用平台叫用封送處理資料

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

請參閱

概念

在 Managed 程式碼中建立原型

指定字元集

參考

DllImportAttribute