int CColumnTreeWnd::GetMaxColumnWidth(HTREEITEM hItem, int nColumn, int nDepth, BOOL bIgnoreCollapsed) { int nMaxWidth = 0; CString strText = m_Tree.GetItemText(hItem); CString strSub; if (AfxExtractSubString(strSub, strText, nColumn, '\t')) { CDC dc; dc.CreateCompatibleDC(NULL); CFont* pOldFont = dc.SelectObject(m_Tree.GetFont()); // calculate text width nMaxWidth = dc.GetTextExtent(strSub).cx; dc.SelectObject(pOldFont); } // add indent and image space if first column if (nColumn == 0) { int nIndent = nDepth; if (GetWindowLong(m_Tree.m_hWnd, GWL_STYLE) & TVS_LINESATROOT) { nIndent++; } int nImage, nSelImage; m_Tree.GetItemImage(hItem, nImage, nSelImage); if (nImage >= 0) { nIndent++; } nMaxWidth += nIndent * m_Tree.GetIndent(); } if (!bIgnoreCollapsed || (m_Tree.GetItemState(hItem, TVIS_EXPANDED) & TVIS_EXPANDED)) { // process child items recursively HTREEITEM hSubItem = m_Tree.GetChildItem(hItem); while (hSubItem) { int nSubWidth = GetMaxColumnWidth(hSubItem, nColumn, nDepth + 1, bIgnoreCollapsed); if (nSubWidth > nMaxWidth) { nMaxWidth = nSubWidth; } hSubItem = m_Tree.GetNextSiblingItem(hSubItem); } } return nMaxWidth; }
void CColumnTreeView::AdjustColumnWidth(int nColumn, BOOL bIgnoreCollapsed) { int nMaxWidth = GetMaxColumnWidth(m_Tree.GetRootItem(), nColumn, 0, bIgnoreCollapsed); HDITEM hditem; hditem.mask = HDI_WIDTH; m_Header.GetItem(nColumn, &hditem); hditem.cxy = nMaxWidth + 20; m_Header.SetItem(nColumn, &hditem); }