用vc画图当把图复制到剪贴板时怎么通过GetTextExtent得到正确的字符长度完整的示例代码
以下是一个完整的示例代码,它演示了如何使用VC ++来绘制一个简单的图形,并通过GetTextExtent函数获取文本的正确宽度:
#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函数将整数转换为宽字符字符串
原文地址: https://www.cveoy.top/t/topic/epTU 著作权归作者所有。请勿转载和采集!