在 C# 開發中,有時需要呼叫 Windows 底層的 Win32 API 來實現 .NET Framework 未直接提供的功能。透過 System.Runtime.InteropServices 命名空間提供的互操作服務,我們可以輕鬆地在 managed code 中呼叫 unmanaged 的 DLL 函數。本文將以 MessageBox 為例,詳細說明如何定義、引入並呼叫 Win32 API。
using System.Runtime.InteropServices;
DllImport 屬性用於指定 DLL 路徑、進入點名稱、呼叫慣例等資訊。以 user32.dll 中的 MessageBox 為例:
[DllImport("user32.dll", EntryPoint = "MessageBox", ExactSpelling = false)]
public static extern int MessageBox(int hWnd, string text, string caption, uint type);
false 允許執行時期依據字元集自動尋找 MessageBoxA (ANSI) 或 MessageBoxW (Unicode) 版本。HWND → int 或 IntPtr,LPCTSTR → string,UINT → uint。/*
* 撰寫者:zhanghua
* 日期:2008/5/28
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace NetMeeting.API
{
public class Win32
{
[DllImport("user32.dll", EntryPoint = "MessageBox", ExactSpelling = false)]
public static extern int MessageBox(int hWnd, string text, string caption, uint type);
}
}
定義完成後,即可像呼叫普通 static 方法一樣使用:
using System;
using NetMeeting.API;
class Test
{
public static void Main(string[] args)
{
// 參數:視窗控制代碼(0=無)、訊息內容、標題、類型(2=詢問圖示+是/否按鈕)
Win32.MessageBox(0, "hello ,this is a c# invoke win32 api", "test", 2);
}
}
本文僅示範最基本的整數與字串參數傳遞。實務上常遇到結構體、指標、回呼函數 等複雜型別,將於後續文章詳細探討 StructLayout、MarshalAs、delegate 轉函數指標等進階技巧。
掌握 DllImport 與型別對應規則,即可在 C# 中自由呼叫豐富的 Win32 API,極大擴展應用程式能力。記得妥善處理記憶體管理與錯誤碼檢查,確保程式穩定可靠。