How do I implement double buffering and real-time drawing in GDI+?

thebluetropics 1,046 Reputation points
2023-03-18T04:25:33.7366667+00:00

I've tried to repainting the window when there is no message left to process, like this:

while (true) {
    if (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
        if (msg.message == WM_QUIT) break;

        TranslateMessage(&msg);
        DispatchMessageW(&msg);
    } else {
        PaintWindow(hwnd);
    }
}

And here is my PaintWindow() function:

bool PaintWindow(HWND _phwnd) {
    PAINTSTRUCT ps;
    HDC hdc = BeginPaint(_phwnd, &ps);

    RECT clientRect;
    GetClientRect(_phwnd, &clientRect);

    Gdiplus::SolidBrush defaultBrush(Gdiplus::Color(255, 23, 0, 0));
    Gdiplus::FontFamily fontFamily(L"Noto Sans");
    Gdiplus::Font font(&fontFamily, 14, Gdiplus::FontStyleRegular, Gdiplus::UnitPixel);

    Gdiplus::Graphics graphics(hdc);
    graphics.SetPixelOffsetMode(Gdiplus::PixelOffsetModeHalf);

    std::string str = std::to_string(number);
    std::wstring wstr(str.begin(), str.end());

    graphics.DrawString(wstr.c_str(), -1, &font, Gdiplus::PointF(0, 0), &defaultBrush);

    EndPaint(_phwnd, &ps);

    number++;

    return true;
}

I don't know why the window doesn't repaint everytime the PaintWindow() is called outside of the WM_PAINT.

I've tried moving the window a bit further outside the display's region, and yeah, it's updated when I drag the window back.

Note that PaintWindow() is called, I tested by adding the number.

And, how do I implement double buffering in GDI+? In Direct2D, it's done automatically. I have no clue of how to do that in GDI+.

Windows development Windows API - Win32
{count} votes

1 answer

Sort by: Most helpful
  1. Xiaopo Yang - MSFT 12,731 Reputation points Microsoft External Staff
    2023-03-20T03:17:03.73+00:00

    Hello @thebluetropics,

    Try to use Off-Screen DC for Flicker-Free. See Flicker-Free Displays Using an Off-Screen DC. Also see When to Draw in a Window. And as far as Double Buffering concerned, the back buffer should be rendered in the background.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.