操作帶結構體的 API 比簡單 API 複雜,但掌握流程後,整個 API 世界將在掌握中。以下以 GetSystemInfo API 取得系統完整資訊為例。
建立 C# Form 專案,加入 Button,代碼視窗匯入:
using System.Runtime.InteropServices;
使用 StructLayout(LayoutKind.Sequential) 確保記憶體配置順序與 Win32 結構一致:
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEM_INFO
{
public uint dwOemId;
public uint dwPageSize;
public uint lpMinimumApplicationAddress;
public uint lpMaximumApplicationAddress;
public uint dwActiveProcessorMask;
public uint dwNumberOfProcessors;
public uint dwProcessorType;
public uint dwAllocationGranularity;
public uint dwProcessorLevel;
public uint dwProcessorRevision;
}
[DllImport("kernel32")]
static extern void GetSystemInfo(ref SYSTEM_INFO pSI);
protected void button1_Click(object sender, System.EventArgs e)
{
try
{
SYSTEM_INFO pSI = new SYSTEM_INFO();
GetSystemInfo(ref pSI);
// 接收回傳結構體後,即可操作其欄位
// e.g. listBox1.InsertItem(0, pSI.dwActiveProcessorMask.ToString());
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
}
StructLayout 屬性控制記憶體配置,Sequential 依宣告順序排列。uint 對應 DWORD 等)。ref 關鍵字傳遞結構體參考,對應 API 的指標參數。DllImport 指定 DLL 名稱(kernel32 會自動尋找 kernel32.dll)。