**Windows API (Win32 API)** 是 Microsoft Windows 作業系統提供給開發人員的**核心函式庫集合**,定義了應用程式與作業系統核心互動的介面。所有 Windows 應用程式 (無論 C++、C#、VB.NET、Delphi、Go、Rust) 最終都透過這組 API 與系統溝通:建立視窗、繪製圖形、管理檔案、執行緒同步、網路通訊、登存取、安全性等。
應用程式 (Your App)
│
▼
框架/執行階段 (.NET CLR, MFC, Qt, WinUI, Electron...)
│
▼
Windows API (User32.dll, Kernel32.dll, Gdi32.dll, Advapi32.dll, Shell32.dll, Comctl32.dll...)
│
▼
Windows Kernel (ntoskrnl.exe) + 驅動程式
│
▼
硬體 (CPU, Memory, GPU, Disk, NIC...)
| DLL | 核心功能 | 常見 C# 對應 |
|---|---|---|
| Kernel32.dll | 程序/執行緒/記憶體/檔案/時間/錯誤處理/載入 DLL | `Process`, `Thread`, `FileStream`, `MemoryMappedFile`, `P/Invoke` |
| User32.dll | 視窗管理、訊息迴路、輸入 (鍵盤/滑鼠)、選單、對話方塊、剪貼簿 | `Form`, `Control`, `MessageBox`, `SetWindowPos`, `RegisterHotKey` |
| Gdi32.dll | 2D 繪圖、字型、筆刷、點陣圖、列印 | `System.Drawing`, `Graphics`, `Bitmap` |
| Advapi32.dll | 登錄、安全性 (ACL、Token)、服務控制、事件日誌 | `RegistryKey`, `EventLog`, `ServiceController` |
| Shell32.dll | Shell 擴充、檔案操作對話框、捷徑、回收筒、工作列 | `OpenFileDialog`, `ShellExecute`, `SHGetKnownFolderPath` |
| Comctl32.dll | 通用控制項 (ListView, TreeView, Toolbar, StatusBar, ProgressBar 6.0+) | `ListView`, `TreeView`, `ProgressBar` (WinForms/WPF 封裝) |
| Ole32.dll / OleAut32.dll | COM 基礎、啟動、封送、Variant、類別工廠 | `Marshal`, `Activator.CreateInstance`, `dynamic` |
| Winhttp.dll / WinInet.dll | HTTP/HTTPS 客戶端 | `HttpClient`, `HttpWebRequest` |
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
// 結構體對齊
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct RECT { public int Left, Top, Right, Bottom; }
// 回傳 BOOL 需 MarshalAs
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
Win32 API 是 Windows 程式設計的**基石**。高階框架讓我們專注於商務邏輯,但當框架不夠用、效能不夠好、或需整合舊代碼時,直接呼叫 Win32 API 是不可或缺的技能。掌握核心 DLL 功能分工、P/Invoke 簽名技巧、記憶體管理與錯誤處理,能讓開發者在需要時突破框架限制,發揮系統最大潛能。