参考别人代码,重载的一个 MFC 的 CListBox 的类。
ZListBox.h
class CZListBox : public CListBox
{
DECLARE_DYNAMIC(CZListBox)
public:
CZListBox();
virtual ~CZListBox();
protected:
DECLARE_MESSAGE_MAP()
private:
CFont _Font;
public:
virtual void DrawItem(LPDRAWITEMSTRUCT /*lpDrawItemStruct*/);
virtual void MeasureItem(LPMEASUREITEMSTRUCT /*lpMeasureItemStruct*/);
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
};
ZListBox.cpp
// CZListBox
IMPLEMENT_DYNAMIC(CZListBox, CListBox)
CZListBox::CZListBox()
{
_Font.CreateFont( 14, 0, 0, 0, FW_NORMAL, FALSE, FALSE, 0, ANSI_CHARSET,
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
DEFAULT_PITCH || FF_SWISS, _T("Consolas") );
}
CZListBox::~CZListBox()
{
_Font.DeleteObject();
}
BEGIN_MESSAGE_MAP(CZListBox, CListBox)
END_MESSAGE_MAP()
// CZListBox 消息处理程序
BOOL CZListBox::PreCreateWindow(CREATESTRUCT& cs)
{
cs.style &= ~LBS_SORT;
cs.style |= LBS_OWNERDRAWFIXED;
return CListBox::PreCreateWindow(cs);
}
void CZListBox::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
LPCTSTR lpszText = (LPCTSTR)lpDrawItemStruct->itemData;
CDC dc;
dc.Attach( lpDrawItemStruct->hDC );
CFont *pFont = dc.SelectObject( &_Font );
if( ODS_SELECTED & lpDrawItemStruct->itemState ) {
dc.SetTextColor( GetSysColor(COLOR_HIGHLIGHTTEXT) );
dc.SetBkColor( GetSysColor(COLOR_HIGHLIGHT) );
dc.FillSolidRect( &lpDrawItemStruct->rcItem, GetSysColor(COLOR_HIGHLIGHT) );
lpDrawItemStruct->rcItem.left += 8;
dc.DrawText( lpszText, _tcslen(lpszText), &lpDrawItemStruct->rcItem, DT_LEFT | \
DT_SINGLELINE | DT_VCENTER );
}
else {
dc.SetTextColor( RGB(0, 0, 0) );
if( lpDrawItemStruct->itemID % 2 )
dc.FillSolidRect( &lpDrawItemStruct->rcItem, RGB(238, 220, 130) );
else
dc.FillSolidRect( &lpDrawItemStruct->rcItem, RGB(127, 255, 212) );
dc.DrawText( lpszText, _tcslen(lpszText), &lpDrawItemStruct->rcItem, DT_LEFT | \
DT_SINGLELINE | DT_VCENTER );
}
dc.SelectObject( pFont );
dc.Detach();
}
void CZListBox::MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct)
{
lpMeasureItemStruct->itemHeight = 30;
}
使用代码:
_ZListBox.Create( WS_CHILD |WS_VISIBLE | WS_BORDER | WS_VSCROLL | WS_HSCROLL | \
LBS_OWNERDRAWVARIABLE, CRect(300, 20, 500, 220), this, IDC_LIST_BOX );
_ZListBox.AddString( _T("Hello !") );
_ZListBox.AddString( _T("What's this ?") );
_ZListBox.AddString( _T("This is an apple !") );
效果图: