Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am trying to determine at run time how many characters I can fit on a line in a multi-line CEdit control.
Here is the code:

BOOL CSegmentsPage::OnInitDialog( void )
{
    CPropertyPage::OnInitDialog();
    BOOL bRet = m_font.CreatePointFont( 100, _T("Courier New") );
    
    m_editSegments.SetFont( &m_font );
    // calculate the number of characters per line.
    CRect r;
    CDC* pDC = m_editSegments.GetDC();
    
    CFont* pFont = pDC->GetCurrentFont();
    LOGFONT logFont;
    pFont->GetLogFont( &logFont );
    //logFont.lfFaceName == _T("System")

    m_editSegments.GetClientRect( &r );
    CSize sizeChar = pDC->GetTextExtent( CString(_T("1")) );
    m_nCharsPerLine = r.Width() / sizeChar.cx;

...


The problem is that the font the CDC is using is not the same as the font i set on the CEdit control(Courier New), it is using "System" font instead. Does anyone know how to fix this?

Thanks - John
Posted

I would use CClientDC[^] instead of calling GetDC() from edit control.
Also try to manually select the created font in your client DC like this:
C++
// Here you create the font and call SetFont for your edit control...
//...
// Now create a client DC for the edit control and select the created font
CClientDC dc(&m_editSegments);
CFont* pOldFont = dc.SelectObject(&m_font);
CSize size = dc.GetTextExtent("....");
dc.SelectObject(pOldFont);


I've used something similar before and it worked for me.

NOTE: In case you need the average char width of the selected font you could use:
C++
// Get text metrics
TEXTMETRIC txtMetric;
memset(&txtMetric, 0, sizeof(txtMetric));
dc.GetTextMetrics(&txtMetric);
// Now "txtMetric.tmAveCharWidth" contains the average char width


I hope this helps :)
 
Share this answer
 
v2
Comments
Nish Nishant 11-Feb-11 7:57am    
Voted 5, proposed as answer.
Nuri Ismail 11-Feb-11 9:18am    
Thanks a lot! :)
Thats great, worked just fine.

Thanks Nuri!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900