ListBox 水平滚动条智能滚动的实现方法

本文详细介绍了如何使用MFC创建一个自定义的列表框控件,包括类的继承、属性的添加、操作方法的实现及在对话框中的应用。通过实例演示了如何增加控件的功能,如添加字符串、刷新水平滚动条,并提供了测试代码验证功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.  选菜单Insert/New Class,设新创建类的名字为CMyListBox,其基类为CListBox,其它选项采用缺省值。单击OK,VC自动生成MyListBox.cppMyListBox.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;
}



























评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值