MFC开发中经常要用到组合框,界面设计的时候为了美观,将组合框设为固定宽度,但是有可能下拉后的文本比组合框宽度宽,导致内容显示不全。不过,可以根据组合框中最长的字符串、组合框字体来计算出组合框下拉部分应该具有的宽度,再设置即可。具体代码如下:
CComboBox* pmyComboBox = (CComboBox*)GetDlgItem(IDC_COMBOX);
ASSERT(pmyComboBox);
// Find the longest string in the combo box.
CString str;
CSize sz;
int dx = 0;
TEXTMETRIC tm;
CDC* pDC = pmyComboBox->GetDC();
CFont* pFont = pmyComboBox->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 < pmyComboBox->GetCount(); i++)
{
pmyComboBox->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);
pmyComboBox->ReleaseDC(pDC);
// Adjust the width for the vertical scroll bar and the left and right border.
dx += ::GetSystemMetrics(SM_CXVSCROLL) + 2*::GetSystemMetrics(SM_CXEDGE);
// Set the horizontal extent so every character of all strings can
// be scrolled to.
pmyComboBox->SetDroppedWidth(dx);