如何控制 ComboBox 中下拉列表框的宽度

MyD*_*Day 3 winapi mfc atl

有没有办法控制win32中COMBOBOX下拉列表的宽度?

And*_*kle 5

我的应用程序类中有一个公共方法:

void CSoundRotaApp::UpdateComboDroppedWidth(CComboBox& rCombo)
{
    int iWidth = theApp.GetRequiredComboDroppedWidth(rCombo);
    if (iWidth > rCombo.GetDroppedWidth())
        rCombo.SetDroppedWidth(iWidth);
}
Run Code Online (Sandbox Code Playgroud)

其中调用此方法:

int CSoundRotaApp::GetRequiredComboDroppedWidth(CComboBox& rCombo)
{
    CString    str;
    CSize      sz;
    int        dx = 0;
    TEXTMETRIC tm;
    CDC*       pDC = rCombo.GetDC();
    CFont*     pFont = rCombo.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 < rCombo.GetCount(); i++)
    {
        rCombo.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);
    rCombo.ReleaseDC(pDC);

    // Adjust the width for the vertical scroll bar and the left and right border.
    dx += ::GetSystemMetrics(SM_CXVSCROLL) + 2 * ::GetSystemMetrics(SM_CXEDGE);

    return dx;
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。

  • 这段代码对我来说看起来很合理,但我想知道*为什么*你需要使用它。我从来不需要自定义组合框的下拉宽度。它总是开箱即用,即使您正在动态地添加或删除项目! (2认同)