The answer is (or at least can be) somewhat non-trivial.
First of all, there are two separate heights you can choose from: the height of the characters themselves, or the height of cell in which a "normal" character lives (but, for example, letters with descenders like y
will usually extend outside the cell). So, for the same size of font, the character cell will usually be slightly larger than the size of the characters themselves.
To choose the font based on the character cell height, you pass a positive number for the height. To choose based on the height of the characters themselves, you pass a negative number (and its absolute value will be used as the height).
So let's assume that you want the characters themselves to be 11 points tall (so we'll need to pass a negative number for the height), and that you want the width to be the default for the font at hand. Let's also assume that you're dealing with MM_TEXT mode, where a logical unit is equal to one pixel.
As Windows uses the term, one point is 1/72nd of an inch (note: 72 points to the inch isn't universal--for example, some use 72.72 points to the inch instead--feel free to modify the following code if you need to comply with a different definition of a "point").
So, to compute the size, we can start by retrieving the number of pixels per inch (vertically) on the screen, then compute the number of pixels for the right number of points:
static const int points_per_inch = 72;
int pixels_per_inch = GetDeviceCaps(hDC, LOGPIXELSY);
int pixels_height = - (points * pixels_per_inch / points_per_inch);
[Microsoft has a MulDiv
function to assure against an intermediate value overflowing in that computation, but unless you're using a 16-bit machine or a truly immense font, that's mostly a solution in search of a problem.]
Since we want the default width, we'll pass 0 for the width.
So, we end up with something like this:
HFONT font = CreateFont(pixels_height, 0, // size
0, 0, 0, // normal orientation
FW_NORMAL, // normal weight--e.g., bold would be FW_BOLD
false, false, false, // not italic, underlined or strike out
DEFAULT_CHARSET,
OUT_OUTLINE_PRECIS, // select only outline (not bitmap) fonts
CLIP_DEFAULT_PRECIS,
CLEARTYPE_QUALITY,
VARIABLE_PITCH | FF_SWISS,
"Arial");