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.
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
<BEGIN LARRYS CODE>
HDC hdc = CreateCompatibleDC(NULL);
RECT rcText = {0, 0, 88, 34};
DrawText(hdc, L"My Text String", -1, &rcText, DT_CENTER | DT_END_ELLIPSIS | DT_EDITCONTROL | DT_WORDBREAK | DT_NOPREFIX | DT_CALCRECT);
CAtlString string;
string.Format(L"Text String occupies: %d x %d pixels", rcText.right - rcText.left, rcText.bottom - rcText.top);
MessageBox(hWnd, string, L"String Size", 0);
<END LARRYS CODE>
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
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.