How do I create a button control (with CreateWindow of a BUTTON window class) that has a standard system-wide size (especially height) that’s consistent with the rest of Windows applications? I should of course take DPI into account and probably other settings.
Remark: Using
USE_CW_DEFAULTfor width and height results in a 0, 0 size button, so that’s not a solution.
In the perfect, hassle-free world…
To create a standard size button we would have to do this:
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 (tmHeightandtmAveCharWidthof theTEXTMETRICstruct respectively) and translate them with MulDiv on your own, unless you are in a dialog, thenMapDialogRect()will do all the job for you.Note that
tmAveCharWidthonly approximates the actual average character width so it’s recommended to use aGetTextExtentPoint32()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_GETIDEALSIZEmessageButton_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.