ComboBox

一、设置下拉组合框自动适应字符串宽度:

1、重载CComboBox类

2、响应 CBN_DROPDOWN 消息

3、添加如下代码:void CMyComboBox::OnDropdown()
{
 this->RecalcDropWidth();
}

void CMyComboBox::RecalcDropWidth()
{
 int num = this->GetCount();
 int nWidth = 0;
 CString str;
 CClientDC dc(this);

 int nSave = dc.SaveDC();
 dc.SelectObject(GetFont());  //考虑字体与字号变化时的宽度调整
 int nScrollWidth = ::GetSystemMetrics(SM_CXVSCROLL); //下拉框的滚动条的宽度
 for (int i=0;i<num;i++)
 {
  GetLBText(i,str);
  int nLen = dc.GetTextExtent(str).cx+nScrollWidth;
  nWidth = max(nWidth,nLen);
 }

 nWidth += dc.GetTextExtent("0").cx;
 dc.RestoreDC(nSave);
 this->SetDroppedWidth(nWidth);
}

你可能感兴趣的:(dropdown)