Question

Currently i'm drawing the text from a textbox in my window. I successfully get the text i need to draw and it draws the text. It's ok.

Here's the problem: when i write something else in my input box and draw the text again (via button push), the new text is drawn right on top of the previous text as to be expected.

I'm new to all of this and i can't find a way to clear the previous text before drawing the new text.

Here's my code:

void DrawMyText(HWND hwnd) {

    int iTextLength = GetWindowTextLength(hDrawInput) + 1;
    char cDrawText[1000] = "";
    HDC wdc = GetWindowDC(hwnd);    
    RECT canvas;
    canvas.left   = 168;
    canvas.top    = 108;
    canvas.right  = 500;
    canvas.bottom = 500;

    GetWindowText(hDrawInput, cDrawText, iTextLength);

    SetTextColor(wdc, 0x00FF0066);
    SetBkMode(wdc,TRANSPARENT);
    DrawText(wdc, cDrawText, -1, &canvas, DT_LEFT);

    DeleteDC(wdc);
}

Any tips on how to do this? I will gladly provide any additional information if needed. Thanks in advance!

Was it helpful?

Solution

DrawText is more like a spray can - it paints over top whatever is already there. I'd recommend switching to SetWindowText. The difference is DrawText is more like a canvas rendering call, and doesn't consider much about the type of control it's drawing to. SetWindowText is an explicit "set the text of this window to this specific value", and is specific to text-based controls. More to the point, it will replace the current text with the new text value.

If you absolutely must do it with DrawText (i.e. you prefer a canvas approach as above), then you'll have to manually clear the text area yourself with something like InvalidateRect() (using the RECT of the text area). Or, by drawing a rectangle equal in size to the text area and with the same color as the background. Let me know if that's not enough detail.

OTHER TIPS

If some other window covers and then uncovers the place where you drew the text it will be gone! The illusion that windows can sit on top of each other is destroyed! Windows provides a scheme to overcome this problem but you are not cooperating with the scheme.

Paint your text only in response to the WM_PAINT message, using the BeginPaint and EndPaint API calls. On the button click just call InvalidateRect, which asks Windows to send you a WM_PAINT. BeginPaint erases your window just before you paint. So by putting your painting code in the right place - the WM_PAINT handler - you solve two problems: It erases any old text, and it repaints whenever your window is uncovered.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top