How to get the height and width of a tooltip dynamically in c++?

  • 9 months ago
Comment

ChatGPT
1 / 1

To get the height and width of a tooltip dynamically in C++, you can use the WinAPI functions GetTextMetrics and DrawText. Here's an example of how you can do it:

cpp
#include <windows.h>

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_CREATE:
{
// Create a tooltip control
HWND hwndTT = CreateWindowEx(WS_EX_TOPMOST, TOOLTIPS_CLASS, NULL,
WS_POPUP | TTS_ALWAYSTIP | TTS_NOPREFIX,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
hwnd, NULL, GetModuleHandle(NULL), NULL);

// Set up tooltip text
TOOLINFO ti;
ti.cbSize = sizeof(TOOLINFO);
ti.uFlags = TTF_IDISHWND | TTF_SUBCLASS;
ti.hwnd = hwnd;
ti.uId = (UINT_PTR)hwnd;
ti.lpszText = LPSTR_TEXTCALLBACK;
SendMessage(hwndTT, TTM_ADDTOOL, 0, (LPARAM)&ti);

break;
}

case WM_NOTIFY:
{
if (((LPNMHDR)lParam)->code == TTN_GETDISPINFO)
{
LPNMTTDISPINFO pDispInfo = (LPNMTTDISPINFO)lParam;
if (pDispInfo->hdr.idFrom == (UINT_PTR)hwnd)
{
// Calculate the size of the tooltip text
RECT rect = { 0, 0, 0, 0 };
HDC hdc = GetDC(hwnd);
HFONT hFont = (HFONT)SendMessage(hwnd, WM_GETFONT, 0, 0);
HFONT hOldFont = (HFONT)SelectObject(hdc, hFont);

DrawText(hdc, "Tooltip Text", -1, &rect, DT_CALCRECT);

SelectObject(hdc, hOldFont);
ReleaseDC(hwnd, hdc);

// Set the tooltip size
pDispInfo->szText.cx = rect.right - rect.left;
pDispInfo->szText.cy = rect.bottom - rect.top;
}

break;
}
}

case WM_DESTROY:
{
PostQuitMessage(0);
break;
}

default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASS wc = { 0 };
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.lpszClassName = "TooltipExample";
RegisterClass(&wc);

HWND hwnd = CreateWindow(wc.lpszClassName, "Tooltip Example",
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
400, 300, NULL, NULL, hInstance, NULL);

ShowWindow(hwnd, nCmdShow);

MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}

return (int)msg.wParam;
}

In this example, when you hover over the window with your mouse, a tooltip with dynamic height and width will appear based on the size of the text "Tooltip Text." The tooltip size is calculated using DrawText with DT_CALCRECT flag. The WM_NOTIFY message is used to respond to the tooltip request for display information. Make sure to adjust the code to fit your actual use case and UI framework.