Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text width in MFC

I'm wanting to dynamically resize a CButton to the width of the text within it. Is there either a built-in way to do this in MFC, or a way of calculating the pixel width of some specified text (so that I can use CWnd::SetWindowPos)?

like image 648
Smashery Avatar asked Nov 16 '09 23:11

Smashery


2 Answers

It's tedious. You need to use CWnd::GetFont() on the button to get the font it's using, and then use the standard GetTextText on a CDC object where you will have selected that font. It looks something like

CClientDC dc( &button );
CFont * pOldFont = dc.SelectObject( button.GetFont() );
 ... dc.GetTextExtent...
dc.SelectObject( pOldFont);
like image 141
fredr Avatar answered Oct 23 '22 05:10

fredr


You can use CDC::GetTextExtent to calculate the width of text in a certain font. Use CWnd::GetDC to get the Device Context from the control displaying the text.

like image 22
demoncodemonkey Avatar answered Oct 23 '22 05:10

demoncodemonkey