要創建一個純 WinAPI 窗口,你需要完成以下步驟:
windows.h
頭文件,該頭文件包含了創建窗口所需的函數和宏定義。#include <windows.h>
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
// 處理其他消息
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
}
RegisterClassEx
函數注冊一個窗口類。WNDCLASSEX wc = {0};
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszClassName = L"WinAPIClass";
if (!RegisterClassEx(&wc))
{
MessageBox(NULL, L"窗口類注冊失敗!", L"錯誤", MB_ICONERROR);
return 1;
}
CreateWindowEx
函數創建一個窗口實例。HWND hwnd = CreateWindowEx(
0,
L"WinAPIClass",
L"WinAPI 窗口",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
500, 400,
NULL,
NULL,
hInstance,
NULL
);
if (hwnd == NULL)
{
MessageBox(NULL, L"窗口創建失敗!", L"錯誤", MB_ICONERROR);
return 1;
}
ShowWindow
函數顯示窗口。ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
GetMessage
或 PeekMessage
函數進入消息循環。MSG msg = {0};
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
完整示例代碼:
#include <windows.h>
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// 注冊窗口類
WNDCLASSEX wc = {0};
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszClassName = L"WinAPIClass";
if (!RegisterClassEx(&wc))
{
MessageBox(NULL, L"窗口類注冊失敗!", L"錯誤", MB_ICONERROR);
return 1;
}
// 創建窗口
HWND hwnd = CreateWindowEx(
0,
L"WinAPIClass",
L"WinAPI 窗口",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
500, 400,
NULL,
NULL,
hInstance,
NULL
);
if (hwnd == NULL)
{
MessageBox(NULL, L"窗口創建失敗!", L"錯誤", MB_ICONERROR);
return 1;
}
// 顯示窗口
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
// 消息循環
MSG msg = {0};
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
這樣你就創建了一個純 WinAPI