源碼
當(dāng)利用業(yè)余時(shí)間開(kāi)發(fā)完成紛飛(Outplay...)一個(gè)類(lèi)似Outlook的客戶(hù)端的郵件程序后 ,發(fā)現(xiàn)Outlook的新郵件的顯示使用單列不同的顏色,酷酷的,于是決定,也該讓我的 Outplay如此...
說(shuō)做就做,就立刻查找了codeguru里的關(guān)于CTreeView的文章,找到了一些合適的信息,大概花了30分鐘的時(shí)間,終于讓我的紛飛(Outplay...)也酷了一把。
Follow me,你會(huì)發(fā)現(xiàn)它是如此的簡(jiǎn)單和便捷,僅僅需要在你的CTreeView中添加幾行代碼而已。
該怎么做呢?(as below)
首先假定你的CTreeView派生類(lèi)CTreeViewEx,然后你需要在TreeViewEx.h中,添加如下行:
afx_msg void OnCustomDraw(NMHDR* pNMHDR, LRESULT* pResult);
然后你需要在消息映射中添加: ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnCustomDraw)
在OnCusteomDraw消息處理例程中添加如下代碼: void CLeftView::OnCustomDraw(LPNMHDR pNmhdr, LRESULT* pResult)
{
static CRect rcItem;
static int nItemState;
LPNMTVCUSTOMDRAW pCustomDraw = (LPNMTVCUSTOMDRAW)pNmhdr;
switch (pCustomDraw->nmcd.dwDrawStage)
{
case CDDS_PREPAINT:
// 這種情況必須處理,且必須將pResult設(shè)置為 CDRF_NOTIFYITEMDRAW,
// 否則父窗口怎么也收不到 CDDS_ITEMPREPAINT 通知消息 (GGH)
*pResult = CDRF_NOTIFYITEMDRAW;
// 重新定位視圖窗口,這樣 TreeCtrl 的 DefWindowProc 不會(huì)重畫(huà)
//::SetViewportOrgEx(pCustomDraw->nmcd.hdc, /*m_nOffset*/0, 0, NULL);
break;
case CDDS_ITEMPREPAINT:
// 設(shè)置背景和前景顏色
nItemState = pCustomDraw->nmcd.uItemState;
pCustomDraw->nmcd.uItemState &= ~CDIS_FOCUS;
pCustomDraw->clrText = m_colHilightText;
// 記住繪制項(xiàng)目的矩形
m_pTree->GetItemRect((HTREEITEM) pCustomDraw->nmcd.dwItemSpec, rcItem, TRUE);
*pResult = CDRF_NOTIFYPOSTPAINT;
break;
case CDDS_ITEMPOSTPAINT:
DrawTreeItem(nItemState, rcItem, pCustomDraw->nmcd.hdc,
(HTREEITEM) pCustomDraw->nmcd.dwItemSpec);
break;
default:
*pResult = CDRF_DODEFAULT;
}
}
最后你需要做的只是在DrawTreeItem中自繪你想要的得效果就是了如下: void
CLeftView::DrawTreeItem(int nItemState, CRect rcItem, HDC hdc, HTREEITEM hItem)
{
// 如果此項(xiàng)獲得輸入焦點(diǎn),則繪制外圍矩形并用藍(lán)色填充矩形區(qū)域
COLORREF colText = m_colText;
if(nItemState & CDIS_FOCUS)
{
::FillRect(hdc, rcItem, (HBRUSH)m_BackBrush.m_hObject);
// 新的焦點(diǎn)矩形代碼......
::DrawFocusRect( hdc, rcItem);
colText = m_colHilightText;
}
else if(nItemState & CDIS_SELECTED)
{
::FillRect(hdc, rcItem, (HBRUSH)m_GrayBrush.m_hObject);
}
else
{
TRACE("CLEAR HIGH\n");
// 清除剩余的高亮條
::FillRect(hdc, rcItem, (HBRUSH)m_BackBrushNormal.m_hObject);
}
// 總是要寫(xiě)沒(méi)有背景的文本
::SetBkMode(hdc, TRANSPARENT);
::SetTextColor(hdc,colText);
CString str = m_pTree->GetItemText(hItem);
::DrawText(hdc, str, -1, rcItem, DT_VCENTER DT_SINGLELINE DT_WORD_ELLIPSIS);
int nNew = 20;
CString strNew = _T("");
strNew.Format(_T("(%d)"),nNew);
::SetTextColor(hdc,RGB(0,0,255));
RECT rc = rcItem;
rc.left = rcItem.right+2;
rc.right = rc.left + 100;
::FillRect(hdc, rc, (HBRUSH)m_BackBrushNormal.m_hObject);
::DrawText(hdc,strNew, -1, rc, DT_VCENTER DT_SINGLELINE DT_WORD_ELLIPSIS);
}
需要說(shuō)明的是如果你想支持拖放,那么你必需要做一些修改......