一般來說,構建一個 Windows 程式可以分為如下幾個步驟:定義視窗類(WNDCLASS)註冊視窗類(RegisterClass)創建視窗(CreateWindow)更新顯示視窗(UpdateWindow、ShowWindow)建立消息迴圈(GetMessage)處理消息(DispatchMess... ...
一般來說,構建一個 Windows 程式可以分為如下幾個步驟:
- 定義視窗類(WNDCLASS)
- 註冊視窗類(RegisterClass)
- 創建視窗(CreateWindow)
- 更新顯示視窗(UpdateWindow、ShowWindow)
- 建立消息迴圈(GetMessage)
- 處理消息(DispatchMessage)
消息處理由視窗過程(WndProc)來完成,消息分為隊列消息和非隊列消息兩種:
- 隊列消息:Windows 放入消息隊列的消息,在消息迴圈中被檢索(GetMessage),然後分發投遞到視窗過程中(DispatchMessage)。
- 非隊列消息:Windows 對視窗過程的直接調用(將消息直接發送到視窗過程)
Windows 示常式序代碼:
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CREATE: /* 視窗創建時的消息處理 */ return 0; case WM_PAINT: hdc = BeginPaint(hwnd, &ps); /* 視窗重繪的消息處理 */ EndPaint(hwnd, &ps); return 0; case WM_DESTROY: /* 視窗銷毀時的消息處理 */ PostQuitMessage(0); return 0; } /* 預設的視窗過程消息處理 */ return DefWindowProc(hwnd, message, wParam, lParam); } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { LPCTSTR lpszClassName = TEXT("demo"); /* 定義視窗類 */ WNDCLASS wndclass; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndclass.hInstance = hInstance; wndclass.lpszClassName = lpszClassName; wndclass.lpszMenuName = NULL; wndclass.lpfnWndProc = WndProc; wndclass.style = CS_HREDRAW | CS_VREDRAW; /* 註冊視窗類 */ if (!RegisterClass(&wndclass)) { MessageBox(NULL, TEXT("This Program requires Windows NT!"), lpszClassName, MB_ICONERROR); return 0; } /* 創建視窗 */ HWND hwnd = CreateWindow( lpszClassName, TEXT("Demo Window"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL ); /* 更新顯示視窗 */ UpdateWindow(hwnd); ShowWindow(hwnd, nCmdShow); /* 消息迴圈 */ MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; }