自绘标准CTreeCtrl的实现(NM_CUSTORMDRAW方法)

自绘树CTreeCtrl可以自己用子类化在派生类里的OnPaint里绘制也可以响应

NM_CUSTORMDRAW这个反射消息,然后绘制,NM_CUSTORMDRAW里有个什么绘画周期的概念,他可以在不同的绘画段

绘制不同的内容,这里具体细节不再赘述,读者可以参考MSDN,这里主要阐述NM_CUSTORMDRAW的绘制方式:

void CSkinTreeCtrl::OnNMCustomdraw(NMHDR *pNMHDR, LRESULT *pResult) { LPNMCUSTOMDRAW pNMCD = reinterpret_cast<LPNMCUSTOMDRAW>(pNMHDR); LPNMTVCUSTOMDRAW lpnmcd = (LPNMTVCUSTOMDRAW) pNMCD; if (lpnmcd ->nmcd.dwDrawStage == CDDS_PREPAINT) { *pResult = CDRF_NOTIFYITEMDRAW; return; } else if (lpnmcd->nmcd.dwDrawStage == CDDS_ITEMPREPAINT) { CRect rcItem(pNMCD->rc); // Item的区域 POINT ptItem ; ptItem.x = rcItem.left + 1 ; ptItem.y = rcItem.top + 1 ; UINT uFlags; HTREEITEM hItem = HitTest(ptItem, &uFlags); // Item 句柄 if(!hItem) { *pResult = CDRF_DODEFAULT; return; } CRect rcClient; GetClientRect(&rcClient); rcItem.left=0; rcItem.right=rcClient.right; rcItem.NormalizeRect(); HDC hdcItem = pNMCD->hdc ; // Item的dc CDC dc; dc.Attach(hdcItem); int nSave = dc.SaveDC(); dc.FillSolidRect(&rcItem,RGB(234, 237, 242)); //draw something CString strText; strText=GetItemText(hItem); if (GetItemState(hItem, TVIS_SELECTED) == TVIS_SELECTED) { CImage img; if (GetFocus() == this) { img.LoadFromResource(AfxGetResourceHandle(), IDB_TREE_SELECT_BKG); } else { img.LoadFromResource(AfxGetResourceHandle(), IDB_TREESELECT_NOFOCUS_BKG); } img.Draw(dc,rcItem); img.Destroy(); } rcItem.left += 30; dc.SetTextColor(RGB(0,0,0)); dc.SetBkMode(TRANSPARENT); CFont font; font.CreateFont(12, // nHeight 0, // nWidth 0, // nEscapement 0, // nOrientation FW_NORMAL, // nWeight FALSE, // bItalic FALSE, // bUnderline 0, // cStrikeOut ANSI_CHARSET, // nCharSet OUT_DEFAULT_PRECIS, // nOutPrecision CLIP_DEFAULT_PRECIS, // nClipPrecision DEFAULT_QUALITY, // nQuality DEFAULT_PITCH | FF_SWISS, // nPitchAndFamily TEXT("宋体")); dc.SelectObject(&font); dc.DrawText(strText, strText.GetLength(), &rcItem, DT_LEFT | DT_SINGLELINE | DT_VCENTER); rcItem.left -= 30; dc.RestoreDC(nSave); dc.Detach(); *pResult = CDRF_SKIPDEFAULT; return; } *pResult = CDRF_DODEFAULT; return; } BOOL CSkinTreeCtrl::OnEraseBkgnd(CDC* pDC) { CRect rcClient; GetClientRect(&rcClient); pDC->FillSolidRect(&rcClient,RGB(234, 237, 242)); return TRUE; } 

 

ui demo:

 

自绘标准CTreeCtrl的实现(NM_CUSTORMDRAW方法)_第1张图片

你可能感兴趣的:(UI,tree)