0

I am trying to track an object's position with GDI in C++ and to draw that position over application's display by creating a rectangle. The object changes position slightly quite often and while the object is standing still or moving the rectangle I'm drawing is flickering.

Initialization:

TargetWnd = FindWindow(nullptr, "app name");
frontbuffer_HDC = GetDC(TargetWnd);
backbuffer_HDC = CreateCompatibleDC(frontbuffer_HDC);
frontbuffer_bitmap = CreateCompatibleBitmap(frontbuffer_HDC, 1920, 1080);
SelectObject(backbuffer_HDC, frontbuffer_bitmap);
Brush = CreateSolidBrush(RGB(255, 0, 0));

This function is called in a 5ms loop:

DrawBorderBox(coords[0], coords[1], x, y, 1);

void DrawBorderBox(int x, int y, int w, int h, int thickness)
{

    DrawFilledRect(x, y, w, thickness);
    BitBlt(frontbuffer_HDC, x, y, w, thickness, backbuffer_HDC, x, y, SRCCOPY);

    DrawFilledRect(x, y, thickness, h);
    BitBlt(frontbuffer_HDC, x, y, thickness, h, backbuffer_HDC, x, y, SRCCOPY);

    DrawFilledRect((x + w), y, thickness, h);
    BitBlt(frontbuffer_HDC, x+w, y, thickness, h, backbuffer_HDC, x, y, SRCCOPY);

    DrawFilledRect(x, y + h, w + thickness, thickness);
    BitBlt(frontbuffer_HDC, x, y+h, w+thickness, thickness, backbuffer_HDC, x, y, SRCCOPY);

}

void DrawFilledRect(int x, int y, int w, int h)
{
    RECT rect = { x, y, x + w, y + h };
    FillRect(backbuffer_HDC, &rect, Brush);
}

Any idea what's going on? The rectangle in copied correctly from the backbuffer to frontbuffer, but the flickering is still there.

Thanks!

Andrei
  • 9
  • 1
  • `5ms` is pretty low, maybe your GPU can't run the loop at 200fps, what if you lower the framerate? – XCS Oct 22 '17 at 17:20
  • Are you trying to draw on some window you don't own? Anyway, your double buffering code is worthless as you are copying from back buffer into target after every draw call. You should copy final image only once. – user7860670 Oct 22 '17 at 17:24
  • With a 100ms delay, the flickering is a lot worse, the rectangle barely being visible. Without a delay between position readings, the flickering is almost gone, but the CPU usage is very high. @VTT I am drawing over a window I don't own, yes. Also, I can't copy the entire backbuffer with a single call because the background is black and I only need the drawn rectangles from it. (which in this case are red) – Andrei Oct 22 '17 at 17:25
  • Clearly the window is redrawing itself quickly again and the pixels you splattered on it don't survive. Splattering at a higher rate does *not* stop the window from redrawing itself. You'll just misinterpret that redraw as "flicker". This isn't going anywhere without much deeper surgery, you need advice from the app's developer. – Hans Passant Oct 22 '17 at 17:51

0 Answers0