C++ Windows GDI+实现自定义圆角边框和按钮颜色
C++ Windows GDI+实现自定义圆角边框和按钮颜色
本文介绍如何使用 C++ 和 Windows GDI+ 库函数对控件进行自定义绘制,实现圆角边框和自定义按钮颜色,并保证不遮挡控件上的文字。
代码示例cpp#include <windows.h>#include <gdiplus.h>
using namespace Gdiplus;
void DrawCustomControl(HWND hwnd, COLORREF borderColor = RGB(0, 0, 0), COLORREF buttonColor = RGB(255, 255, 255)) { HDC hdc = GetDC(hwnd); RECT rect; GetClientRect(hwnd, &rect);
// 创建内存绘图上下文 HDC memDC = CreateCompatibleDC(hdc); HBITMAP memBitmap = CreateCompatibleBitmap(hdc, rect.right - rect.left, rect.bottom - rect.top); HBITMAP hOldBitmap = (HBITMAP)SelectObject(memDC, memBitmap);
// 绘制背景色 HBRUSH hBrush = CreateSolidBrush(buttonColor); FillRect(memDC, &rect, hBrush); DeleteObject(hBrush);
// 绘制圆角矩形边框 HPEN hPen = CreatePen(PS_SOLID, 2, borderColor); SelectObject(memDC, hPen); RoundRect(memDC, rect.left, rect.top, rect.right, rect.bottom, 10, 10); DeleteObject(hPen);
// 将绘制结果复制到窗口的设备上下文 BitBlt(hdc, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, memDC, 0, 0, SRCCOPY);
// 清理资源 SelectObject(memDC, hOldBitmap); DeleteObject(memBitmap); DeleteDC(memDC);
ReleaseDC(hwnd, hdc);}
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps);
// 调用自定义绘制函数 DrawCustomControl(hwnd, RGB(255, 0, 0), RGB(0, 0, 255));
EndPaint(hwnd, &ps); return 0; } case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hwnd, msg, wParam, lParam);}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // 初始化 GDI+ GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
// 创建窗口 WNDCLASSEX wc = {0}; wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = WndProc; wc.hInstance = hInstance; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wc.lpszClassName = L'WindowClass'; RegisterClassEx(&wc);
HWND hwnd = CreateWindowEx(0, L'WindowClass', L'Window', WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 500, 300, NULL, NULL, hInstance, NULL); ShowWindow(hwnd, nCmdShow);
MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); }
// 释放 GDI+ GdiplusShutdown(gdiplusToken);
return (int)msg.wParam;}
代码解释
DrawCustomControl函数: - 接收控件句柄hwnd、边框颜色borderColor和按钮颜色buttonColor作为参数。 - 使用GetDC获取控件的设备上下文。 - 使用GetClientRect获取控件的矩形区域。 - 创建内存绘图上下文memDC,用于绘制操作。 - 创建兼容位图memBitmap,并将其选入内存绘图上下文。 - 使用FillRect函数填充背景色。 - 使用CreatePen函数创建画笔,并使用RoundRect函数绘制圆角矩形边框。 - 使用BitBlt函数将内存绘图上下文中的内容复制到窗口的设备上下文中。 - 清理资源,包括内存绘图上下文、位图、画笔等。2.WndProc函数: - 在窗口消息处理函数中,处理WM_PAINT消息。 - 在WM_PAINT消息处理中,调用DrawCustomControl函数进行自定义绘制。3.WinMain函数: - 初始化 GDI+ 库。 - 创建窗口并设置窗口消息处理函数。 - 处理消息循环,直到程序退出。 - 释放 GDI+ 库。
使用方法
将 DrawCustomControl 函数添加到您的代码中,并在需要自定义绘制控件的地方调用该函数。您可以根据需要修改边框颜色和按钮颜色参数。
注意: 以上代码示例仅供参考,您可能需要根据实际需求进行调整
原文地址: https://www.cveoy.top/t/topic/UOP 著作权归作者所有。请勿转载和采集!