How can I know the width of string

I want the width of a CString to determinate font, how can I know?
I want to know if the CStatic associated has enough size
Thanks in advance
[160 byte] By [Alicante] at [2007-11-18 19:16:19]
# 1 Re: How can I know the width of string
get the DC of the Static control then call :
CDC::GetTextExtent( const CString& str );
hspc at 2007-11-11 1:18:03 >
# 2 Re: How can I know the width of string
thanks hscp
Alicante at 2007-11-11 1:19:06 >
# 3 Re: How can I know the width of string
Originally posted by hspc
get the DC of the Static control then call :
CDC::GetTextExtent( const CString& str );
Almost perfect ;) , but to retrieve the correct size, you must
select the appropriate font into the device context before GetTextExtent.
See next example:
CString strText = _T("Ala-bala portocala, iesi Gheorghitza...");
CDC* pDC = m_static.GetDC();

CFont* pFont = m_static.GetFont();
CFont* pfontOld = pDC->SelectObject(pFont);
CSize size = pDC->GetTextExtent(strText);
pDC->SelectObject(pfontOld);

CRect rc;
m_static.GetWindowRect(rc);
m_static.SetWindowPos(NULL, 0, 0, size.cx, rc.Height(),
SWP_NOMOVE|SWP_NOZORDER);
m_static.SetWindowText(strText);
Do comment the blue code above to see what happens.
ovidiucucu at 2007-11-11 1:20:05 >
# 4 Re: How can I know the width of string
BTW, MS recommends to call ReleaseDC after you have used GetDC():CString strText = _T("Ala-bala portocala, iesi Gheorghitza...");
CDC* pDC = m_static.GetDC();

if(pDC)
{
CFont* pFont = m_static.GetFont();
CFont* pfontOld = pDC->SelectObject(pFont);
CSize size = pDC->GetTextExtent(strText);
pDC->SelectObject(pfontOld);

CRect rc;
m_static.GetWindowRect(rc);
m_static.SetWindowPos(NULL, 0, 0, size.cx, rc.Height(),
SWP_NOMOVE|SWP_NOZORDER);
m_static.SetWindowText(strText);
m_static.ReleaseDC(pDC);
}
VictorN at 2007-11-11 1:21:05 >
# 5 Re: How can I know the width of string
Originally posted by VictorN
BTW, MS recommends to call ReleaseDC after you have used GetDC()
Yes, true.
Anyhow, I have posted just few sample lines and not a whole function.
BTW, some people recommend if(NULL != pDC)
instead of if(pDC)... :)
ovidiucucu at 2007-11-11 1:22:01 >
# 6 Re: How can I know the width of string
Agree... :D :thumb:
VictorN at 2007-11-11 1:23:11 >