Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical centering of multi-line cstatic text in MFC

How can one make a CStatic with text auto-wrap (multiline) which vertically centeres the result in the control's rectangle?

The problem I'm trying to solve is this: I have a CStatic control next to a CComboBox which updates information text depending on the choice. This text can be either short or long, requiring the CStatic to sometimes use multi-lines, and sometimes not. I want the info-text be vertically center-aligned with the CComboBox.

Now here is the problem:

  • If I make the CStatic only 1 textline high, it looks good for 1-line texts, but multi-lines do not fit and are not displayed.

  • If I make the CStatic higher to fit 2 lines, it looks good for long texts (with 2 lines), but 1-line-texts are shifted upwards, as the CStatic aligns the text on the top. A CStatic with the behavior mentioned in the question would solve this...

If I can't easily get a vertically centered CStatic multi-line control, the alternative would be to resize the control rect depending on the amount of text in it. But in this case I have a different problem:

How can I programatically find out how many lines a text will need in a CStatic of specific width?

like image 331
BmyGuest Avatar asked Oct 06 '22 01:10

BmyGuest


1 Answers

Unfortunately you can't vcenter multi-line text in a CStatic.

Your next question has a solution but it's a bit of a pain to use. What you do is you use CDC::DrawTextEx with the DT_CALCRECT flag to get the size (in pixels) of the text you want to format. By dividing that by the height of a line of text (given in the font info you can get from the DC, plus some spacing which I'm not sure of how much that is - presumably it's a fixed amount, I don't think you can specify line spacing with DrawText), you will get (an approximation of) the number of lines you will get. You can then resize the control rect.

Come to think of it, you are probably better off not converting to lines and just resize your control to the extent you get from DrawTextEx :)

Things like this usually require some experimentation to get exactly right, and sometimes behave differently between OS versions. Proceed with caution.

like image 172
Roel Avatar answered Oct 10 '22 03:10

Roel