DevC++ 5.11 上编译 Windows API 代码:绘制长方形

在 DevC++ 5.11 上编译 Windows API 的代码,需要做一些修改。以下是修改后的代码,该代码可以绘制一个红色的长方形,并填充蓝色。

```cpp #include

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

void square(HDC hdc, int x, int y, int width, int height, COLORREF borderColor, COLORREF fillColor) { // 创建画笔和画刷 HPEN hPen = CreatePen(PS_SOLID, 1, borderColor); HBRUSH hBrush = CreateSolidBrush(fillColor);

// 选择画笔和画刷
SelectObject(hdc, hPen);
SelectObject(hdc, hBrush);

// 绘制长方形
Rectangle(hdc, x, y, x + width, y + height);

// 释放画笔和画刷
DeleteObject(hPen);
DeleteObject(hBrush);

}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // 注册窗口类 WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, IDI_APPLICATION); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = NULL; wcex.lpszClassName = "MyWindowClass"; wcex.hIconSm = LoadIcon(wcex.hInstance, IDI_APPLICATION);

if (!RegisterClassEx(&wcex))
{
    MessageBox(NULL, "窗口类注册失败!", "错误", MB_ICONERROR);
    return 0;
}

// 创建窗口
HWND hWnd = CreateWindow("MyWindowClass", "My Window", WS_OVERLAPPEDWINDOW,
    CW_USEDEFAULT, CW_USEDEFAULT, 800, 600, NULL, NULL, hInstance, NULL);

if (!hWnd)
{
    MessageBox(NULL, "窗口创建失败!", "错误", MB_ICONERROR);
    return 0;
}

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

// 消息循环
MSG msg;
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) { HDC hdc; PAINTSTRUCT ps;

switch (message)
{
case WM_PAINT:
    hdc = BeginPaint(hWnd, &ps);
    square(hdc, 100, 100, 200, 200, RGB(255, 0, 0), RGB(0, 0, 255));
    EndPaint(hWnd, &ps);
    break;
case WM_DESTROY:
    PostQuitMessage(0);
    break;
default:
    return DefWindowProc(hWnd, message, wParam, lParam);
}

return 0;

}

<p>修改后的代码将绘制长方形的功能封装在一个函数中,然后在窗口的 `WM_PAINT` 消息中调用该函数来绘制长方形。
</p>
DevC++ 5.11 上编译 Windows API 代码:绘制长方形

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

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