1. 选菜单Insert/New Class,设新创建类的名字为CMyListBox,其基类为CListBox,其它选项采用缺省值。单击OK,VC自动生成MyListBox.cpp和MyListBox.h两个文件。
2.接下来将主对话框的列表框改为MyJListBox类型,即在CLassView扩展CCustomListBoxDlg类并双击m_lListTest成员,在编辑窗格,修改
CListBox m_lListTest;
为:
CMyListBox m_lListTest;
然后,在类声明代码之前,插入
#include "MyListBox.h"
3.CMyListBox类中增加
class CMyListBox : public CListBox
{
// Construction
public:
CMyListBox();
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMyListBox)
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CMyListBox();
int AddString(LPCTSTR lpszItem);
void RefreshHorizontalScrollBar(void);
// Generated message map functions
protected:
//{{AFX_MSG(CMyListBox)
// NOTE - the ClassWizard will add and remove member functions here.
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
4.添加相应的实现
int CMyListBox::AddString(LPCTSTR lpszItem)
{
int nResult = CListBox::AddString(lpszItem);
RefreshHorizontalScrollBar();
return nResult;
}
void CMyListBox::RefreshHorizontalScrollBar(void)
{
CDC *pDC = this->GetDC();
if ( NULL == pDC )
{
return;
}
int nCount = this->GetCount();
if ( nCount < 1 )
{
this->SetHorizontalExtent( 0 );
return;
}
int nMaxExtent = 0;
CString szText;
for ( int i = 0; i < nCount; ++i )
{
this->GetText( i, szText );
CSize &cs = pDC->GetTextExtent( szText );
if ( cs.cx > nMaxExtent )
{
nMaxExtent = cs.cx;
}
}
this->SetHorizontalExtent( nMaxExtent );
}
5.测试
m_ListBox.AddString("this is a test, this is a test, this is a test, this is a test, this is a test, this is a test, ");
m_ListBox.AddString("这是一个测试的例子,这是一个测试的例子,这是一个测试的例子,这是一个测试的例子,这是一个测试的例子");
m_ListBox.AddString("");//使得始终显示最新的一行</span>
if (nCount > 0)
m_ListBox.SetCurSel(nCount - 1);//使得始终显示最新的一行</span></span>
GetDlgItem(IDC_BUTTON_START)->EnableWindow(TRUE);
UpdateData(TRUE);
6.清除CListBox控件显示内容
m_ListBox.ResetContent();
UpdateData(FALSE);
7.在线程中更新显示
UINT ThreadFun2(CMutil_Thread3Dlg *p)
{
p->m_ListBox.AddString("123456");
return 1;
}