I have a program which draw a Rectangle under mouse cursor and show the pixel color, but I can’t manage it to clear the shape inside the while loop, if I use ‘InvalidateRect()‘ it clear rectangle too fast and flickering, if not use ‘InvalidateRect()‘ then Rectangle keep duplicating like THIS, how to fix that?
HWND hwnd;
POINT p;
unsigned short R=0, G=0, B=0;
void drawRect()
{
GetCursorPos(&p);
HDC hdc = GetDC(NULL);
HPEN border = CreatePen(PS_SOLID, 2, RGB(0, 0, 0));
HBRUSH background = CreateSolidBrush(RGB(R, G, B));
SelectObject(hdc, border);
SelectObject(hdc, background);
Rectangle(hdc, p.x+10, p.y+10, p.x+40, p.y+40);
DeleteObject(border);
DeleteObject(background);
}
void init()
{
while (GetAsyncKeyState(VK_RBUTTON) & 0x8000)
{
grabPixel(); //get RGB color from cursor coordination
drawRect(); //draw preview rectangle under cursor
InvalidateRect(hwnd, NULL, true);
}
}
Note: it doesn’t have WinMain() or WndProc()
There are all sorts of things wrong with this. What are you actually trying to do?
From the fact that you’re using
GetDC(NULL), it looks like this is supposed to be drawing a rectangle on the entire screen.Where is the
hwndvalue coming from? If that window does have a message loop (and it probably does), then that’s the window being invalidated and redrawing itself.A note:
InvalidateRectmerely marks the rectangle as needing-to-be-painted the next time that that application’s (actually thread’s, more-or-less) message queue is empty.UpdateWindowwill cause aWM_PAINTmessage to be sent immediately.drawRectisn’t cleaning up properly, either. It should callReleaseDCwhen it’s finished, and it ought to restore the previous drawing objects after it’s finished (and most definitely before it deletes them) as well:What you probably want to do is, when selection starts, create a window the size of the screen and copy the existing screen into it. Then you can draw all over that intelligently.
The
DrawDragRectfunction (see my blog) is designed for this sort of thing.