視窗程式處理訊息的核心函數,由系統呼叫 (非應用程式主動呼叫)。每個視窗類別關聯一個視窗程序,處理該類別視窗接收的所有訊息。
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
hwnd:接收訊息的視窗控制代碼message:訊息識別碼wParam/lParam:訊息相關參數
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return 0;
}
DefWindowProc:系統預設處理,確保未處理訊息不被丟棄PostQuitMessage(0):發送 WM_QUIT 至訊息佇列,結束 GetMessage 迴圈
typedef struct tagWNDCLASS {
UINT style; // 類別風格 (CS_HREDRAW | CS_VREDRAW 等)
WNDPROC lpfnWndProc; // 視窗程序指標
int cbClsExtra; // 類別額外位元組
int cbWndExtra; // 視窗實例額外位元組
HINSTANCE hInstance; // 應用程式實例
HICON hIcon; // 類別圖示
HCURSOR hCursor; // 類別游標
HBRUSH hbrBackground; // 背景刷子
LPCSTR lpszMenuName; // 選單資源名
LPCSTR lpszClassName; // 類別名稱 (唯一)
} WNDCLASS;
#include
// 視窗程序前向宣告
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow) {
HWND hwnd;
MSG msg;
WNDCLASS wc = {0};
char szClassName[] = "MyWindowClass";
char szTitle[] = "My First Windows API Program";
// 1. 定義視窗類別
wc.style = 0;
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)GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName = szClassName;
// 2. 註冊視窗類別
if (!RegisterClass(&wc)) {
MessageBeep(0);
return FALSE;
}
// 3. 建立視窗
hwnd = CreateWindow(
szClassName, szTitle,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hInstance, NULL);
// 4. 顯示與更新
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
// 5. 訊息迴圈
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
// 視窗程序實作
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return 0;
}
WinMain 執行初始化RegisterClass 向系統登記視窗類別CreateWindow 建立視窗實例,系統發送 WM_CREATE → WndProcShowWindow 顯示視窗,系統發送 WM_PAINT → WndProc (此程式未處理,交給 DefWindowProc 留白)GetMessage 迴圈等待訊息WM_CLOSE → DefWindowProc 呼叫 DestroyWindow → WM_DESTROY → PostQuitMessage → 迴圈結束gcc main.c -o main.exe -mwindows學習 GDI 繪圖,在 WM_PAINT 中繪製文字、圖形、位圖,打造真正有畫面的程式。