Question

I want to show on the screen some value, that are changeable. I have following code

void CMainWnd::OnPaint()
{
    CPaintDC dc(this);
    CRect rcText( 0, 0, 500 ,500 );

    wchar_t text[36];       
    unsigned int num = server->GetNumClients(num);
    wsprintf(text, L"Number of connected clients: %d", num);

    dc.DrawText(text, &rcText, DT_LEFT);
    CFrameWnd::OnPaint();
}

 void CMainWnd::OnTimer(UINT timerID)
 {
     SendMessage(WM_PAINT, 0, 0);
 }

It draws text when window appears. But in next calls when text is different the text on the screen didn't change. Using the debugger I can see that OnPaint was called, text has been changed, but on my window text remains the same. GetLastError() returns 0. I think I'm missing something important how DrawText works. I tried to call UpdateWindow() in the end, but nothing changed. For some reason screen is not updates..

Was it helpful?

Solution

You should not send a paint message directly, but instead invalidate the area to be repainted (InvalidateRect(&area) ) and let the system handle it. By only sending a paint, you don't get anything because the system says 'There's no area that needs painting, so for efficiency I won't bother' - or rather, the clip area that constrains painting will be empty (no update area). By invalidating an area you tell the system that that area needs repainting, so the next paint call will have a valid clip area and you will see a change.

(Better to use wsprintf_s() with the buffer size - in fact, as you appear to be using MFC use CString and CString::Format() instead - and you should not call the base class OnPaint() (it has no effect, since when the CPaintDC goes out of scope it clears any update area).

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