首页 > 代码库 > 动态创建自绘的CListBox注意事项

动态创建自绘的CListBox注意事项

Create(WS_VISIBLE|WS_CHILD|LBS_NOTIFY|LBS_OWNERDRAWFIXED|LBS_HASSTRINGS|LBS_NOINTEGRALHEIGHT ,rcWnd,this,xxx);

如果想要响应ON_LBN_SELCHANGE消息,则一定要加LBS_NOTIFY;

如果想要自绘风格则加LBS_OWNERDRAWFIXED;

如果碰到DrawItem的时候,GetText获取不到正常的字符串的时候,则要加LBS_HASSTRINGS;

如果碰到改变列表框大小的时候,列表框高度不对劲,则要加LBS_NOINTEGRALHEIGHT;

顺便贴出自绘代码段:

void CMyListBox::DrawItem(LPDRAWITEMSTRUCT lpDIS) 
{
	if ((int)lpDIS->itemID < 0)
		return; 

	TCHAR ch[64] = {0};
	GetText(lpDIS->itemID, ch);

	CDC* pDC = CDC::FromHandle(lpDIS->hDC);
	CRect	rFrame	= lpDIS->rcItem;
	rFrame.DeflateRect(1,1,1,1);

	// If item has been selected, draw the highlight rectangle using the item‘s color.
	CBrush brush(RGB(255,255,255));
	pDC->FillRect(&rFrame, &brush);

	if ((lpDIS->itemState & ODS_SELECTED))
	{
		CBrush brush(RGB(51,153,255));
		pDC->FillRect(&rFrame, &brush);
		pDC->SetTextColor(RGB(20,0,0)); 
	}

	int nBkMode = pDC->SetBkMode(TRANSPARENT);
	UINT nFormat = DT_LEFT | DT_SINGLELINE | DT_VCENTER;
	if (GetStyle() & LBS_USETABSTOPS)
		nFormat |= DT_EXPANDTABS;
	CFont font;
	font.CreatePointFont(120, _T("宋体"));
	pDC->SelectObject(&font);
	// Calculate the rectangle size before drawing the text.
	pDC->DrawText(ch,-1, &rFrame, nFormat);
	pDC->SetBkMode(nBkMode);

	DeleteObject(&font);
}	

  

动态创建自绘的CListBox注意事项