设置组合框下拉文本的宽度

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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值