C++ Windows.h 绘制窗口和红色长方形 - 示例代码
以下是使用 C++ 和 Windows.h 库绘制窗口并绘制一个红色长方形的示例代码:\n\ncpp\n#include \"Windows.h\"\n\nLRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);\n\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)\n{\n // Register the window class.\n const char CLASS_NAME[] = \"Sample Window Class\";\n\n WNDCLASS wc = {0};\n\n wc.lpfnWndProc = WindowProc;\n wc.hInstance = hInstance;\n wc.lpszClassName = CLASS_NAME;\n\n RegisterClass(&wc);\n\n // Create the window.\n HWND hwnd = CreateWindowEx(\n 0,\n CLASS_NAME,\n \"Sample Window\",\n WS_OVERLAPPEDWINDOW,\n CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,\n NULL,\n NULL,\n hInstance,\n NULL\n );\n\n if (hwnd == NULL)\n {\n return 0;\n }\n\n ShowWindow(hwnd, nCmdShow);\n\n // Run the message loop.\n MSG msg = {0};\n while (GetMessage(&msg, NULL, 0, 0))\n {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n\n return 0;\n}\n\nLRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)\n{\n switch (uMsg)\n {\n case WM_PAINT:\n {\n PAINTSTRUCT ps;\n HDC hdc = BeginPaint(hwnd, &ps);\n\n // Get the dimensions of the client area.\n RECT rect;\n GetClientRect(hwnd, &rect);\n int width = rect.right - rect.left;\n int height = rect.bottom - rect.top;\n\n // Calculate the dimensions of the rectangle.\n int rectWidth = width * 3 / 4;\n int rectHeight = height;\n\n // Create a red brush.\n HBRUSH hBrush = CreateSolidBrush(RGB(255, 0, 0));\n\n // Select the red brush into the device context.\n HBRUSH hOldBrush = (HBRUSH)SelectObject(hdc, hBrush);\n\n // Draw the red rectangle.\n Rectangle(hdc, 0, 0, rectWidth, rectHeight);\n\n // Restore the old brush.\n SelectObject(hdc, hOldBrush);\n\n // Delete the red brush.\n DeleteObject(hBrush);\n\n EndPaint(hwnd, &ps);\n }\n break;\n case WM_DESTROY:\n PostQuitMessage(0);\n return 0;\n }\n\n return DefWindowProc(hwnd, uMsg, wParam, lParam);\n}\n\n\n该代码通过创建一个窗口并处理窗口的消息来实现绘制红色长方形。在WM_PAINT消息中,通过获取窗口的客户区域的尺寸,计算出矩形的尺寸,并使用CreateSolidBrush函数创建一个红色画刷,然后使用SelectObject函数将这个画刷选择到设备上下文中。最后,使用Rectangle函数绘制一个红色矩形。绘制完成后,使用EndPaint函数结束绘制过程。\n\n请注意,这仅是一个简单的示例,用于演示如何使用Windows.h库在C++中绘制窗口和矩形。在实际开发中,可能需要添加更多的错误检查和处理代码。
原文地址: https://www.cveoy.top/t/topic/pIkm 著作权归作者所有。请勿转载和采集!