C++ WinAPI TextOut() update text

yop picture yop · Feb 26, 2014 · Viewed 13.5k times · Source

I'm creating a Windows application with WinAPI. I'm using the TextOut() function to display updated text to the user when handling the WM_PAINT message for the window.

case WM_PAINT:
{
     PAINTSTRUCT ps;
     HDC hdc;
     hdc = BeginPaint(hwnd, &ps);
     SelectObject(hdc, hfDefault);

     // display the user data in the window
     TextOut(hdc,10,70, "Points: 0", 9);
     TextOut(hdc,10,85, "Level: 0", 8);

     // ...
     EndPaint(hwnd, &ps);
}
break;

How can I change the text printed by TextOut() after the function is called as well as the last parameter that determines the length of the printed text?

Everything I've found about using TextOut() was about the text font.

Answer

Johnny Mopp picture Johnny Mopp · Feb 26, 2014

Maybe something like this....

// I'll assume hwnd is global
void OnSomeActionToRefreshValues()
{
    HDC hdc = ::GetDc(hwnd);
    DrawValues(hdc, 88, 99);
    ReleaseDC(hdc);
}

void DrawValues(HDC hdc, int points, int level)
{
    // Might need a rectangle here to overwrite old text
    SelectObject(hdc, hfDefault);    // I assume hfDefault is global
    TCHAR text[256];
    swprintf_s(text, 256, L"Points: %d", points);
    TextOut(hdc, 10, 70, text, wcslen(text));
    swprintf_s(text, 256, L"Level: %d", level);
    TextOut(hdc, 10, 85, text, wcslen(text));
}

And in you win proc:

case WM_PAINT:
    PAINTSTRUCT ps;
    HDC hdc;
    hdc = BeginPaint(hwnd,&ps);
    DrawValues(hdc, 88, 99);
    EndPaint(hwnd,&ps);
    break;