创建一个基本的 Win32 窗口

时间:2021-09-23 16:39:40
 #include <Windows.h>

 //Forward declarations
bool InitMainWindow(HINSTANCE, int);
LRESULT CALLBACK MsgProc(HWND, UINT, WPARAM, LPARAM); //Constants
const int WIDTH = ;
const int HEIGHT = ; HWND hwnd = NULL; int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
//Initialize the window
if (!InitMainWindow(hInstance, nCmdShow))
{
return ;
} //Main message loop
MSG msg = {};
while (WM_QUIT != msg.message)
{
if (PeekMessage(&msg, NULL, , , PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
} return static_cast<int>(msg.wParam);
} bool InitMainWindow(HINSTANCE hInstance, int nCmdShow)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(wcex);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.cbClsExtra = ;
wcex.cbWndExtra = ;
wcex.lpfnWndProc = MsgProc;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wcex.lpszClassName = "Basic Win32 Window";
wcex.lpszMenuName = NULL;
wcex.hIconSm = LoadIcon(NULL, IDI_WINLOGO); //Register window class
if (!RegisterClassEx(&wcex))
{
return false;
} //Create window
hwnd = CreateWindow(
"Basic Win32 Window",
"Win32 Window",
WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION,
GetSystemMetrics(SM_CXSCREEN) / - WIDTH / ,
GetSystemMetrics(SM_CYSCREEN) / - HEIGHT / ,
WIDTH,
HEIGHT,
(HWND)NULL,
(HMENU)NULL,
hInstance,
(LPVOID*)NULL); if (!hwnd)
{
return false;
} ShowWindow(hwnd, nCmdShow); return true;
} LRESULT CALLBACK MsgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_DESTROY:
PostQuitMessage();
return ; case WM_CHAR:
switch (wParam)
{
case VK_ESCAPE:
PostQuitMessage();
return ;
}
return ;
} return DefWindowProc(hwnd, msg, wParam, lParam);
}