Paweł Błaszkiewicz
Paweł Błaszkiewicz

Reputation: 11

How can I clear TextOut?

How can I delete or hide the current textout to add new text? currently, as he adds another textout, the text overlaps the text. I tried to use InvalidateRect(hWnd, NULL, TRUE); but I don't see any difference.

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    PAINTSTRUCT ps;
    HDC hdc;

    switch (message)
    {
    case WM_PAINT:
        hdc = BeginPaint(hWnd, &ps);
                TextOut(hdc, 5, 5, text.c_str(), _tcslen(_T(text.c_str())));
                EndPaint(hWnd, &ps);
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
        break;
    }

    return 0;
}

Upvotes: 0

Views: 842

Answers (3)

AlainD
AlainD

Reputation: 6625

Another technique is to re-draw the text with the background colour, something like:

HDC hdc = ::GetDC(this->m_hWnd);
SetBkMode(hdc, TRANSPARENT);

SetTextColor(hdc, clrBackground);
TextOut(hdc, 5, 5, text.c_str(), _tcslen(_T(text.c_str())));

UpdateTextSomewhere(&text);

SetTextColor(hdc, clrText);
TextOut(hdc, 5, 5, text.c_str(), _tcslen(_T(text.c_str())));
::ReleaseDC(this->m_hWnd, hdc);

clrX are of type COLORREF. They might be set up in the form constructor orOnInitDialog e.g. clrText = RGB(0, 0, 0);.

This technique only works if the form background is a single, solid colour.

Upvotes: 0

Drake Wu
Drake Wu

Reputation: 7190

In your case, the InvalidateRect call will trigger a WM_PAINT message, causing TextOut() to be called again. The answer of @mnistic is a good solution. But I think you should really put TextOut method into the real event handling (such as OnButtonClickEvent) instead of putting it into WM_PAINT.

Upvotes: 0

mnistic
mnistic

Reputation: 11020

Your call to TextOut is in your WM_PAINT handler. This means that the text will always be drawn on each WM_PAINT, making your call to InvalidateRect practically useless.

One way to fix this would be to have a boolean (drawText) to indicate whether you want to draw the text or not. Then in your function to clear the text:

drawText = FALSE;
InvalidateRect(hWnd, NULL, TRUE);

And in your WndProc:

case WM_PAINT:
    {
        hdc = BeginPaint(hWnd, &ps);
        if(drawText)
            TextOut(hdc, 5, 5, text.c_str(), _tcslen(_T(text.c_str())));
        EndPaint(hWnd, &ps);
    }
    break;

Upvotes: 1

Related Questions