方法:重载CCombbox类,生成类CComboBoxDropEx 。
- 头文件内容 ComboBoxDropEx.h
class CComboBoxDropEx : public CComboBox
{
DECLARE_DYNAMIC(CComboBoxDropEx)
public:
CComboBoxDropEx();
virtual ~CComboBoxDropEx();
protected:
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnCbnDropdown();
};
- 实现文件内容 CComboBoxDropEx.cpp
#include "stdafx.h"
#include "xx.h"
#include "ComboBoxDropEx.h"
IMPLEMENT_DYNAMIC(CComboBoxDropEx, CComboBox)
CComboBoxDropEx::CComboBoxDropEx()
{
}
CComboBoxDropEx::~CComboBoxDropEx()
{
}
BEGIN_MESSAGE_MAP(CComboBoxDropEx, CComboBox)
ON_CONTROL_REFLECT(CBN_DROPDOWN, &CComboBoxDropEx::OnCbnDropdown)
END_MESSAGE_MAP()
void CComboBoxDropEx::OnCbnDropdown()
{
// TODO: 在此添加控件通知处理程序代码
CDC* pDC = GetDC();
if (pDC != NULL)
{
CString strText;
CRect rc;
GetClientRect(rc);
int nMaxWidth = rc.Width();
const int nCount = GetCount();
for (int i = 0; i < nCount; i++)
{
GetLBText(i, strText);
CSize size = pDC->GetTextExtent(strText, strText.GetLength());
if (size.cx > nMaxWidth)
{
nMaxWidth = size.cx;
}
}
SetDroppedWidth(nMaxWidth * 0.9);
ReleaseDC(pDC);
}
}