// This hack allows you to determine the height that a cell should be in order to display
// stuff properly in the given width.
CSize CGridCellMultiLine::GetTextExtentEx(int width, LPCTSTR szText, CDC* pDC /*= NULL*/)
{
	CGridCtrl* pGrid = GetGrid();
	ASSERT(pGrid);
	
	BOOL bReleaseDC = FALSE;
	if (pDC == NULL)
	{
		pDC = pGrid->GetDC();
		if (!pDC) 
		{
			CGridDefaultCell* pDefCell = (CGridDefaultCell*) GetDefaultCell();
			ASSERT(pDefCell);
			return CSize(pDefCell->GetWidth(), pDefCell->GetHeight());
		}
		bReleaseDC = TRUE;
	}
	
	CFont *pOldFont = NULL,
	*pFont = GetFontObject();
	if (pFont)
		pOldFont = pDC->SelectObject(pFont);
	
	CSize size;
	int nFormat = GetFormat();
	TEXTMETRIC tm;
	pDC->GetTextMetrics(&tm);

	int textWidth = width - (4*GetMargin ());

	// corrects the bug if resizing column gives a text width smaller than (4*Getmargin())
	if (textWidth <= 0) 
	{
		textWidth = 1;
	}
	
	// If the cell is a multiline cell, then use the width of the cell
	// to get the height
	if ((nFormat & DT_WORDBREAK) && !(nFormat & DT_SINGLELINE))
	{
		CRect rect;
		rect.SetRect(0, 0, textWidth, 0);
		pDC->DrawText(szText, -1, rect, nFormat | DT_CALCRECT);

		size.cx = rect.Width ();
		size.cy = rect.Height ();
	}
	else
		size = pDC->GetTextExtent(szText, _tcslen(szText));
	
	size.cx += (tm.tmOverhang);
	
	if (pOldFont)
		pDC->SelectObject(pOldFont);
	
	size += CSize(4*GetMargin(), 2*GetMargin());
	
	// Kludge for vertical text
	LOGFONT *pLF = GetFont();
	if (pLF->lfEscapement == 900 || pLF->lfEscapement == -900)
	{
		int nTemp = size.cx;
		size.cx = size.cy;
		size.cy = nTemp;
		size += CSize(0, 4*GetMargin());
	}
	
	if (bReleaseDC)
		pGrid->ReleaseDC(pDC);
	
	return size;
}