Can DT_CALCRECT format of DrawText() return the width?

109 views Asked by At

Hi I'm trying to know the required width value for a text to fit a RECT.

So for now I'm trying to get the RECT dimensions according to a LPCWSTR, using the DT_CALCRECT format of DrawText().

Microsoft states that DT_CALCRECT

Determines the width and height of the rectangle. [...] DrawText returns the height of the formatted text[...]

The following code

LPCWSTR textCheck = L"12345";
RECT rectCheck = { 0, 0, 0, 0 };
int check = DrawText(
    hdc,
    textCheck,
    -1,
    &rectCheck,
    DT_CALCRECT);

returns the same value (16), textCheck being "12345" and "123456789".

Is it able to return only the height or I'm missing something?

Is DT_CALCRECT able to determines the width for itself but can't return it?

I expected DT_CALCRECT able to return the width and the height.

2

There are 2 answers

6
selbie On BEST ANSWER

Unless I'm misunderstanding something, if you just want the width needed to render a string (on a single line), combo DT_CALCRECT with DT_SINGLELINE and then inspect the rectCheck which is an out param.

LPCWSTR textCheck = L"12345";
RECT rectCheck = { 0, 0, 0, 0 };
int check = DrawText(
    hdc,
    textCheck ,
    -1,
    &rectCheck ,
    DT_CALCRECT|DT_SINGLELINE);

int requiredWidth = rectCheck.right-rechCheck.left;

0
Alexandre Mazel On

Use GetTextExtentPoint32 to return a tuple (width,rect) of the formatted text

Eg this code in python:

wText, hText = win32gui.GetTextExtentPoint32(handleDC,strText)