#include <Windows.h>

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // 创建窗口类 WNDCLASS wc = { 0 }; wc.lpfnWndProc = WndProc; wc.hInstance = hInstance; wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wc.lpszClassName = L"WindowClass";

// 注册窗口类
if (!RegisterClass(&wc))
{
    return 1;
}

// 创建窗口
HWND hWnd = CreateWindow(
    L"WindowClass",
    L"Square Window",
    WS_OVERLAPPEDWINDOW,
    CW_USEDEFAULT,
    CW_USEDEFAULT,
    800,  // 窗口宽度
    600,  // 窗口高度
    NULL,
    NULL,
    hInstance,
    NULL
);

if (!hWnd)
{
    return 2;
}

// 显示窗口
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);

// 消息循环
MSG msg = { 0 };
while (GetMessage(&msg, NULL, 0, 0))
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}

return (int)msg.wParam;

}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps);

    RECT rect;
    GetClientRect(hWnd, &rect);

    int squareSize = rect.right / 3;  // 正方形边长

    int x = (rect.right - squareSize) / 2;  // 正方形左上角x坐标
    int y = (rect.bottom - squareSize) / 2;  // 正方形左上角y坐标

    // 绘制正方形
    Rectangle(hdc, x, y, x + squareSize, y + squareSize);

    EndPaint(hWnd, &ps);
    break;
}
case WM_DESTROY:
    PostQuitMessage(0);
    break;
default:
    return DefWindowProc(hWnd, message, wParam, lParam);
}

return 0;

}

这段代码使用了Windows.h库中的函数和结构体来创建窗口并处理窗口消息。在WndProc函数中的WM_PAINT消息处理部分,我们获取窗口的客户区域大小,然后计算出正方形的位置和尺寸,并使用Rectangle函数绘制正方形。

你可以将这段代码保存为一个.cpp文件,并使用C++编译器编译运行。运行后会弹出一个窗口,并在窗口中绘制一个正方形,该正方形的边长为窗口宽度的1/3,高度与窗口高度相同。

C++ Windows.h 绘制窗口和正方形:示例代码和解释

原文地址: https://www.cveoy.top/t/topic/pIj4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录