Vertically centering multiline cstatic text in MFC

How do I make a CStatic with automatic text wrapping (multi-line) that vertically centers the result in the control rectangle?

The problem I'm trying to solve is this: I have a CStatic control next to CComboBox that updates the info text based on the selection. This text can be short or long, requiring CStatic to sometimes use multiline lines and sometimes not. I want the info text to be vertically centered with CComboBox.

Now here's the problem:

  • If I make CStatic only 1 text line high, it looks good for text lines, but multi-line lines don't fit and are not displayed.

  • If I make CStatic above to fit 2 lines, it looks good for long texts (with 2 lines), but 1-line texts shift up as CStatic aligns the text on top. CStatic with the behavior mentioned in the question will resolve this ...

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

How can I programmatically find out how many lines it will take for text in a CStatic of a certain width?

+3


source to share


1 answer


Unfortunately, you cannot insert multi-line text in CStatic.

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



Come to think of it, you're probably better off not going to lines and just resizing your control to the extent you get from DrawTextEx :)

This kind of thing usually requires some experimentation to be correct, and sometimes differently between OS versions. Be careful.

+3


source







All Articles