I want to adjust a Static control’s size to its content size, so I need to calculate the size of its text content first. I found a way to use GetTextExtentPoint32 to calculate the size, but I need to set the DC’s font to the same as the control’s font first. Is there a better way to do this? I’ve set the Static control’s font once, I think maybe I don’t need to set the DC’s font the second time.
What is the best way to calculate the size of a Static control’s text content? And is there a better way to autosize the Static control?
It sounds to me like you’ve already figured out the correct way to do it. Call
GetTextExtentPoint32to figure out the ideal size of the control given the text that it contains, and then resizing the control to the calculated size.It’s a lot of work, but that’s what happens when you’re working with the raw Win32 API. You don’t have a handy wrapper library that abstracts all this for you in a
Control.AutoSize()function. You could easily write your own function and re-use it, but the Win32 standard controls do not expose an “auto-size” API.As far as the font, you will definitely need to make sure that the device context is using the same font as the control, otherwise you’ll calculate the wrong size. But you don’t have to create a new device context, request a handle the static control’s font, and select that into your new DC. Instead, you can just use the static control’s DC using the
GetDCfunction and passing in the handle to your static control window. Make sure that if you callGetDC, you always follow up with a call toReleaseDCwhen you’re finished!However, do note some caveats of the
GetTextExtentPoint32function that may interfere with the accuracy of the size you calculate:\n) or carriage returns (\r\n) when computing the height.SS_NOPREFIXstyle.(This is all mentioned in the linked documentation, but does anyone actually read that?)
Perhaps an easier alternative is to draw the text the same way that the static control is already doing. Unless you have the
SS_SIMPLEstyle set (which usesTextOutorExtTextOutto draw text as an optimization), static controls draw their text by calling theDrawTextfunction with the appropriate parameters, given the other control styles that are set (reference).You can do exactly the same thing, and add the
DT_CALCRECTflag in your call to theDrawTextfunction, which causes it to determine the width and height of the rectangle required to draw the specified text without actually drawing the text.