Get text width in MFC

2020-02-12 07:56发布

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)?

4条回答
Juvenile、少年°
2楼-- · 2020-02-12 08:27

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.

查看更多
一纸荒年 Trace。
3楼-- · 2020-02-12 08:38
CClientDC hdc(this);
GetRect.SetRect(0,0,iLabelWidth,0);
//
//To get Height of Lable in advance
//
hdc.DrawText(
                TempData,
                TempData.GetLength(),
                GetRect,
                DT_CALCRECT | DT_MODIFYSTRING | DT_WORDBREAK 
            );
查看更多
兄弟一词,经得起流年.
4楼-- · 2020-02-12 08:41

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);
查看更多
Evening l夕情丶
5楼-- · 2020-02-12 08:42

In addition to @demoncodemonkey's answer, you can call CDC::DrawText with the DT_CALCRECT flag. This way the text won't be drawn, but the CRect you pass to the function will have the width and height of the text to draw.

This is especially useful if you want to draw text with line breaks (using the DT_WORDBREAK flag). You won't be able to do that using CDC::GetTextExtent.

查看更多
登录 后发表回答