爲MFC中的ListBox添加水平滾動條

咱們知道,MFC中的水平滾動條並不像垂直滾動條那樣的智能。當文字超出ListBox的寬度時,水平滾動條並不會本身出現,咱們須要手動的調用CListBox中的函數SetHorizontalExtent設置寬度,單位爲像素。函數

咱們能夠本身添加智能水平滾動條,如今咱們首先隨便建立一個ListBox控件,並將它的HorizontalScrollbar屬性設置爲True,以下:this

 

這樣,控件的建立就完成了,而後就須要添加代碼來實現智能水平滾動條了。spa

首先,咱們建立一個類,這裏,我命名爲CIHListBox,該類須要繼承CListBox類,以便添加水平滾動條。繼承

而後咱們須要覆蓋CListBox類的AddString和InsertString接口以便添加水平滾動條。接口

最後天然就是咱們主要的計算智能水平滾動條的方法了,這裏命名爲RefushHorizontalScrollBar。class

整個類的聲明以下:test

#ifndef _IHLISTBOX_H_
#define _IHLISTBOX_H_List

class CIHListBox: public CListBox
{
public:
CIHListBox(void);
~CIHListBox(void);方法

// 覆蓋該方法以便添加水平滾動條
int AddString( LPCTSTR lpszItem );
int InsertString( int nIndex, LPCTSTR lpszItem );命名

// 計算水平滾動條寬度
void RefushHorizontalScrollBar( void );
};

#endif

首先,AddString和InsertString沒有什麼懸念,就是調用基類的方法後從新計算下水平滾動條的寬度,代碼以下:

int CIHListBox::AddString( LPCTSTR lpszItem )
{
int nResult = CListBox::AddString( lpszItem );

RefushHorizontalScrollBar();

return nResult;
}

int CIHListBox::InsertString( int nIndex, LPCTSTR lpszItem )
{
int nResult = CListBox::InsertString( nIndex, lpszItem );

RefushHorizontalScrollBar();

return nResult;
}

而後就是RefushHorizontalScrollBar方法了,該方法的實質是計算ListBox中每項的寬度,而後將最大寬度設置爲水平寬度。實現代碼以下:

void CIHListBox::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 );
}

而後,咱們在獲取ListBox控件的時候,只須要使用子類的方法就能夠實現智能水平滾動條了。

個人嘗試代碼以下:

#define DLG_LIST_TEST ((CIHListBox*)(GetDlgItem(IDC_LISTTEST)))

DLG_LIST_TEST->AddString( TEXT("This is lenth tes") );
DLG_LIST_TEST->AddString( TEXT("This is lenth test test test") );
DLG_LIST_TEST->AddString( TEXT("This is lenth test test test test test11111") );

結果以下:

 

以上僅供你們參考,謝謝你們^-^!~

相關文章
相關標籤/搜索