It seems to me that you already understood the correct way to do this. Call GetTextExtentPoint32
to determine the ideal size for the control, given the text it contains, and then resize the control to a computed size.
This is a lot of work, but what happens when you work with the raw Win32 API. You do not have a convenient wrapper library that abstracts all this for you in the Control.AutoSize()
function. You can easily write your own function and reuse it, but standard Win32 controls do not provide auto-size APIs.
As for the font, you definitely need to make sure that the device context uses the same font as the control, otherwise you will calculate the wrong size. But you do not need to create a new device context, request a static control font descriptor and select it in your new DC. Instead, you can use constant DC control using the GetDC
function and pass it to the static control window. Make sure that if you call GetDC
, you will always answer the ReleaseDC
call when you are done!
However, pay attention to some caveats of the GetTextExtentPoint32
function that may interfere with the accuracy of the size you are calculating:
- He ignores clipping.
- When calculating the height, new lines (
\n
) or carriage returns ( \r\n
) are not taken into account. - It does not take into account the prefix characters (preceding the line with the ampersand) and is used to indicate keyboard mnemonics if your static control has
SS_NOPREFIX
style . - It cannot return an exact result in the light of kerning, which can be automatically implemented by some devices.
(All of this is mentioned in the related documentation, but does anyone really read this?)
Perhaps a simpler alternative is to draw text in the same way as static control. If you don't have the SS_SIMPLE
style style (which uses TextOut
or ExtTextOut
to draw text as an optimization), static controls draw their text by calling the DrawText
function with the appropriate parameters, taking into account the other control styles that are set ( link ).
You can do the same and add the DT_CALCRECT
flag to your DrawText
function DrawText
, which forces it to determine the width and height of the rectangle needed to draw the specified text, without actually drawing the text.
source share