What’s wrong with this code, part 22 – Drawing Text…

What’s wrong with this code, part 22 – Drawing Text…

Recently I’ve been working on something that I’ve never done before in my almost 24 years at Microsoft.

For the past 23ish years, I’ve been a plumber – all the work I’ve done has been under the covers. But for the next version of Windows, I decided to stretch my boundaries a bit and try some UI programming. I’ve just spent the past few days working on a cool change to the volume control (it’s not important what it is, and most people will never know about the change, but those that do will probably agree with me :)).

As part of the change, I needed to measure the dimensions of a text string. This is a dummy version of some code I wrote, I simply called DrawText with the DT_CALCRECT into a memory DC that I created.

This is just code I took by using Visual Studio to create a Windows Win32 project and inserting the code between “BEGIN LARRYS CODE” and “END LARRYS CODE”. The meat of the code is just 3 lines of code.

Even though there’s almost no code here, it still has a bug in it that was quite subtle and took me several hours to find.

I wonder if it's got something to do with ClearType -- CreateCompatibleDC will (if I remember correctly) give you a DC with a 1x1 black and white (single bit) bitmap initially selected into it.

For bitmap, stroke and TrueType fonts, this won't be a problem -- they render in black and white. I wonder if, for ClearType fonts, it needs a bitmap of the correct colour depth, in case there's a pixel or so of extra ClearType-ness going on.

To get a bitmap of the correct depth, you can use CreateCompatibleBitmap(NULL).

For whatever reason, when you set the system to 144 DPI (large fonts), the default font that's used for the control I'm using to draw the text gets dramatically larger than either the system font OR the default GUI font. Which caused my size calculations to be wrong, which caused some ugly clipping.

Also Justin: Apparently the system font doesn't scale the same as other fonts do.

Nils Arthur

2 Aug 2008 10:16 AM

While we are talking volume controls. Could you explain why it's only possible to lower the volume in Windows (i.e. setting a volume between 0% and 100%) and not raise it (i.e setting it higher than 100%)?