MFC控件增加滚动条

以Listbox Control为例。

        首先,子类化CListBox,重载AddString和InsertString函数;并且根据加入的字符,判断行的宽度,实现RefushHorizontalScrollBar函数,如下:

//HorScrollListBox.h
#include <windows.h>
#include <afxwin.h>
// CHorScrollListBox CListBox

class CHorScrollListBox : public CListBox
{
	DECLARE_DYNAMIC(CHorScrollListBox)

public:
	CHorScrollListBox(CWnd* pParent = NULL);   // standard constructor
	virtual ~CHorScrollListBox();

	int AddString(LPCTSTR lpszItem);
	int InsertString(int nIndex, LPCTSTR lpszItem);

	// 计算水平滚动条宽度
	void RefushHorizontalScrollBar(void);

protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

	DECLARE_MESSAGE_MAP()
};


//
// HorScrollListBox.cpp : implementation file
//

#include "stdafx.h"
#include "HorScrollListBox.h"
#include "afxdialogex.h"


// CHorScrollListBox CListBox
IMPLEMENT_DYNAMIC(CHorScrollListBox, CListBox)

CHorScrollListBox::CHorScrollListBox(CWnd* pParent /*=NULL*/)
	: CListBox()
{

}

CHorScrollListBox::~CHorScrollListBox()
{
}

void CHorScrollListBox::DoDataExchange(CDataExchange* pDX)
{
	CListBox::DoDataExchange(pDX);
}


BEGIN_MESSAGE_MAP(CHorScrollListBox, CListBox)
END_MESSAGE_MAP()


// CHorScrollListBox message handlers
int CHorScrollListBox::AddString(LPCTSTR lpszItem) {
	int nResult = CListBox::AddString(lpszItem);
	RefushHorizontalScrollBar();
	return nResult;
}

int CHorScrollListBox::InsertString(int nIndex, LPCTSTR lpszItem) {
	int nResult = CListBox::InsertString(nIndex, lpszItem);
	RefushHorizontalScrollBar();
	return nResult;
}

// 计算水平滚动条宽度
void CHorScrollListBox::RefushHorizontalScrollBar(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);
}

         在ui界面给界面上的listbox control增加变量,选择刚才子类化CListBox的子类类型,如下:

           选择ui界面上的listbox control修改属性Horizontal Scroll为True,如下:

        添加完毕,运行可以看到效果。

猜你喜欢

转载自blog.csdn.net/JinhuCheng/article/details/84060846