In the perfect, hassle-free world...
To create a standard size button we would have to do this:
LONG units = GetDialogBaseUnits();
m_hButton = CreateWindow(TEXT("BUTTON"), TEXT("Close"),
WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
0, 0, MulDiv(LOWORD(units), 50, 4), MulDiv(HIWORD(units), 14, 8),
hwnd, NULL, hInst, NULL);
where 50 and 14 are respective DLU dimensions, 4 and 8 are horizontal and vertical dialog template units respectively, based on GetDialogBaseUnits()
function documentation remarks.
Nothing's perfect
BUT as Anders pointed out, those metrics are based on the system font. If your window uses a shell dialog font or simply anything not making your eyes bleed, you're pretty much on your own.
To get your own "dialog" base units, you have to retrieve current text metrics with GetTextMetrics()
and use character height and average width (tmHeight
and tmAveCharWidth
of the TEXTMETRIC
struct respectively) and translate them with MulDiv by your own, unless you are in a dialog, then MapDialogRect()
will do all the job for you.
Note that tmAveCharWidth
only approximates the actual average character width so it's recommended to use a GetTextExtentPoint32()
function on an alphabetic character set instead.
See:
Simpler alternative
If buttons are the only control you want to resize automatically, you can also use BCM_GETIDEALSIZE
message Button_GetIdealSize()
macro (Windows XP and up only) to retrieve optimal width and height that fits anything the button contains, though it looks pretty ugly without any margins applied around the button's text.