如何调整Win32列表框的大小以适合其内容? [英] How to resize a Win32 listbox to fit its content?

查看:79
本文介绍了如何调整Win32列表框的大小以适合其内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当项目更改时,是否有任何方法可以调整Win32列表框的大小以适合其内容(将显示其所有内容的最小大小,不需要滚动条)?

Is there any way to resize a Win32 listbox to fit its content (the minimum size that will show all its content, not needing a scrollbar), whenever its items change?

谢谢!

我需要同时调整列表框的宽度和高度.

推荐答案

您没有指定是否同时需要水平和垂直,但我将假设不需要.基本上,您需要获取项目数和项目高度并将它们相乘,然后添加控件边框的空间(除非控件是无边界的,您可能需要尝试一下):

You didn't specify whether you wanted horizontal as well as vertical, but I'm going to assume not. Basically, you need to get the number of items and the item height and multiply them, then add on the space for the control borders (unless the control is borderless, you may need to play around with this):

void AutosizeListBox(HWND hWndLB)
{
    int iItemHeight = SendMessage(hWndLB, LB_GETITEMHEIGHT, 0, 0);
    int iItemCount = SendMessage(hWndLB, LB_GETCOUNT, 0, 0);

    // calculate new desired client size
    RECT rc;
    GetClientRect(hWndLB, &rc);
    rc.bottom = rc.top + iItemHeight * iItemCount;

    // grow for borders
    rc.right += GetSystemMetrics(SM_CXEDGE) * 2;
    rc.bottom += GetSystemMetrics(SM_CXEDGE) * 2;

    // resize
    SetWindowPos(hWndLB, 0, 0, 0, rc.right, rc.bottom, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
}

如果还希望水平调整大小,则需要在DC中选择正确的字体,然后使用 GetTextExtentPoint32 遍历所有项目以计算最大文本长度.

If you want horizontal sizing as well you would need to select the right font into a DC, and loop through all the items to calculate the maximum text length using GetTextExtentPoint32.

添加了一个也计算水平尺寸的版本.

Added a version that calculates horizontal size as well.

void AutosizeListBox(HWND hWndLB)
{
    int iItemHeight = SendMessage(hWndLB, LB_GETITEMHEIGHT, 0, 0);
    int iItemCount = SendMessage(hWndLB, LB_GETCOUNT, 0, 0);

    // get a DC and set up the font
    HDC hDC = GetDC(hWndLB);
    HGDIOBJ hOldFont = SelectObject(hDC, (HGDIOBJ)SendMessage(hWndLB, WM_GETFONT, 0, 0));

    // calculate width of largest string
    int iItemWidth = 0;
    for (int i = 0; i < iItemCount; i++)
    {
        int iLen = SendMessage(hWndLB, LB_GETTEXTLEN, i, 0);
        TCHAR* pBuf = new TCHAR[iLen + 1];
        SendMessage(hWndLB, LB_GETTEXT, i, (LPARAM)pBuf);

        SIZE sz;
        GetTextExtentPoint32(hDC, pBuf, iLen, &sz);
        if (iItemWidth < sz.cx) iItemWidth = sz.cx;

        delete[] pBuf;
    }

    SelectObject(hDC, hOldFont);
    ReleaseDC(hWndLB, hDC);

    // calculate new desired client size
    RECT rc;
    SetRect(&rc, 0, 0, iItemWidth, iItemHeight * iItemCount);

    // grow for borders
    rc.right += GetSystemMetrics(SM_CXEDGE) * 2;
    rc.bottom += GetSystemMetrics(SM_CXEDGE) * 2;

    // resize
    SetWindowPos(hWndLB, 0, 0, 0, rc.right, rc.bottom, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
}

这篇关于如何调整Win32列表框的大小以适合其内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆