#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) { WNDCLASSEX wcex; HWND hWnd; MSG msg;

// 注册窗口类
ZeroMemory(&wcex, sizeof(wcex));
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.hInstance = hInstance;
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszClassName = L"WindowClass";
RegisterClassEx(&wcex);

// 创建窗口
hWnd = CreateWindow(L"WindowClass", L"VC++ Draw Text Demo", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, NULL, NULL, hInstance, NULL);
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);

// 消息循环
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) { PAINTSTRUCT ps; HDC hdc; RECT rect; SIZE size; wchar_t text[] = L"Hello, World!";

switch (message)
{
case WM_PAINT:
    hdc = BeginPaint(hWnd, &ps);

    // 绘制文本
    SetTextColor(hdc, RGB(0, 0, 255));
    SetBkMode(hdc, TRANSPARENT);
    TextOut(hdc, 10, 10, text, wcslen(text));

    // 获取文本宽度
    GetClientRect(hWnd, &rect);
    GetTextExtentPoint32(hdc, text, wcslen(text), &size);
    DrawText(hdc, L"Text Width: " + std::to_wstring(size.cx).c_str(), -1, &rect, DT_SINGLELINE | DT_BOTTOM | DT_RIGHT);

    EndPaint(hWnd, &ps);
    break;

case WM_DESTROY:
    PostQuitMessage(0);
    break;

default:
    return DefWindowProc(hWnd, message, wParam, lParam);
}

return 0;

}

在这个示例中,我们使用 TextOut 函数来绘制文本,并使用 GetTextExtentPoint32 函数获取文本的宽度。我们还使用 DrawText 函数在窗口的右下角显示文本的宽度。注意,我们使用 std :: to_wstring 函数将整数转换为宽字符字符串。

VC++ 绘制图形并获取文本宽度示例代码

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

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