C++Builder、Delphi、VB、C# WinForms 等 RAD 環境提供豐富元件庫,極大提升開發效率。但:
#include
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int nCmdShow)
{
// 1. 註冊視窗類別
WNDCLASS wc = {0};
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszMenuName = NULL;
wc.lpszClassName = TEXT("HelloWinClass");
RegisterClass(&wc);
// 2. 建立視窗實例
HWND hwnd = CreateWindow(
TEXT("HelloWinClass"), TEXT("Hello WinAPI"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hInstance, NULL);
// 3. 顯示與更新
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
// 4. 訊息迴圈
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
{
switch (msg) {
case WM_PAINT: {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
RECT rc; GetClientRect(hwnd, &rc);
DrawText(hdc, TEXT("Hello, WinAPI!"), -1, &rc,
DT_SINGLELINE | DT_CENTER | DT_VCENTER);
EndPaint(hwnd, &ps);
return 0;
}
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, msg, wp, lp);
}
| 結構 | 用途 | 關鍵欄位 |
|---|---|---|
| WNDCLASS | 視窗類別模板 | lpfnWndProc, hInstance, lpszClassName, hbrBackground, hCursor, hIcon |
| MSG | 訊息封裝 | hwnd, message, wParam, lParam, time, pt |
| PAINTSTRUCT | 繪圖資訊 | hdc, rcPaint, fErase |
| RECT | 矩形區域 | left, top, right, bottom |
| POINT | 座標點 | x, y |
| 場景 | RAD 元件限制 | API 方案 |
|---|---|---|
| 全域熱鍵 | 無對應元件 | RegisterHotKey + WM_HOTKEY |
| 系統托盤圖示 | 元件功能受限 | Shell_NotifyIcon (NIM_ADD/MODIFY/DELETE) |
| 自訂視窗形狀/透明/分層 | 無屬性暴露 | SetWindowRgn, SetLayeredWindowAttributes, WS_EX_LAYERED |
| 檔案關聯/右鍵選單擴展 | 完全不支援 | Shell Extension (IContextMenu, IShellExtInit) |
| 低層鍵盤/滑鼠攔截 | 無法觸及 | SetWindowsHookEx (WH_KEYBOARD_LL/MOUSE_LL) |
| 進程記憶體讀寫/注入 | 安全限制 | OpenProcess, VirtualAllocEx, WriteProcessMemory, CreateRemoteThread |

API 不是用來取代 RAD,而是讓你在 RAD 觸及天花板時,依然擁有突破的能力。