Visual c++ 有没有办法在vc+;中动态调整组合列表宽度+;

Visual c++ 有没有办法在vc+;中动态调整组合列表宽度+;,visual-c++,Visual C++,我试图根据列表内容的最大宽度调整组合列表的宽度。 动态增加/减少组合列表宽度的所有可能方法取决于列表项的最大宽度。我使用了以下方法: void SetBestDroppedWidth(CComboBox *pComboBox) { // Find the longest string in the combo box. CString str; CSize sz; int dx = 0; TEXTMETRIC tm;

我试图根据列表内容的最大宽度调整组合列表的宽度。 动态增加/减少组合列表宽度的所有可能方法取决于列表项的最大宽度。

我使用了以下方法:

void SetBestDroppedWidth(CComboBox *pComboBox)
{
    // Find the longest string in the combo box.
    CString     str;
    CSize       sz;
    int         dx = 0;
    TEXTMETRIC  tm;
    CDC*        pDC = pComboBox->GetDC();
    CFont*      pFont = pComboBox->GetFont();

    // Select the listbox font, save the old font
    CFont* pOldFont = pDC->SelectObject(pFont);
    // Get the text metrics for avg char width
    pDC->GetTextMetrics(&tm);
    
    for (int i = 0; i < pComboBox->GetCount(); i++)
    {
        pComboBox->GetLBText(i, str);
        sz = pDC->GetTextExtent(str);

        // Add the avg width to prevent clipping
        sz.cx += tm.tmAveCharWidth;

        if (sz.cx > dx)
            dx = sz.cx;
    }
    // Select the old font back into the DC
    pDC->SelectObject(pOldFont);
    pComboBox->ReleaseDC(pDC);
    
    // Adjust the width for the vertical scroll bar and the left and right border.
    dx += ::GetSystemMetrics(SM_CXVSCROLL) + 2 * ::GetSystemMetrics(SM_CXEDGE);
    
    // If the width of the list box is too small, adjust it so that every
    // item is completely visible.
    if (pComboBox->GetDroppedWidth() < dx)
    {
        pComboBox->SetDroppedWidth(dx);
        ASSERT(pComboBox->GetDroppedWidth() == dx);
    }
}

您使用的是什么API/SDK/框架?MFC,QT,winforms?使用MFC框架谢谢-Lucian。看起来不错。但您必须解释为什么会有剪辑,以及如何知道添加
tm.tmAveCharWidth
就足够了?
//CComboBox         m_HavingRole; // in header file

   for (RoleList::iterator it = rolesObList.begin(); it != rolesObList.end(); it++)
    {
        nItem = m_HavingRole.AddString(it->m_szName);
        m_HavingRole.SetItemData(nItem, it->m_lRoleID);
    }
    SetBestDroppedWidth(&m_HavingRole);