Hi, @Davit First, InvalidateRect function can indirectly generate WM_PAINT
messages for your windows and execute your code in WM_PAINT
again.
How to delete the drawing depends on how you draw it. If you only collect the start and end points as in the second sample, then you only need to invalidate those points in DeleteDrawing()
,like: x=y=-1:
void DeleteDrawing(HWND hwnd)
{
m_drawStart = { -1,-1 };
m_drawEnd = { -1,-1 };
InvalidateRect(hwnd, NULL, TRUE);
}
And when processing the WM_PAINT
message, check the POINTS if they are valid. (This is actually similar to @Viorel 's bool cleared
)
I am not sure how to store objects
If you want to collect not only the start and end points, but a collection of as many points as possible that mouse has moved:
static std::vector<POINT> m_draw;
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
...
case WM_LBUTTONDOWN:
{
SetTimer(hWnd, 1, 10, 0);//Send WM_TIMER message every 10ms to collect current mouse point
POINT pt;
pt.x = GET_X_LPARAM(lParam);
pt.y = GET_Y_LPARAM(lParam);
m_draw.push_back(pt);
}
break;
case WM_TIMER:
{
POINT p;
GetCursorPos(&p);
ScreenToClient(hWnd,&p);
m_draw.push_back(p);
}
break;
case WM_LBUTTONUP:
{
KillTimer(hWnd,1); //stop collection
POINT pt;
pt.x = GET_X_LPARAM(lParam);
pt.y = GET_Y_LPARAM(lParam);
m_draw.push_back(pt);
InvalidateRect(hWnd, NULL, FALSE);//Do not erase the background to keep the previous image
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code that uses hdc here...
HPEN currentPen = CreatePen(PS_SOLID,4, RGB(255, 0, 0));
HPEN OldPen = (HPEN)SelectObject(hdc, currentPen);
//just an example
if (!m_draw.empty())
{
if (m_draw.size() == 1)
{
MoveToEx(hdc, m_draw[0].x, m_draw[0].y, NULL);
LineTo(hdc, m_draw[0].x, m_draw[0].y);
}
else
{
for (int i = 0; i < m_draw.size() - 1; i++)
{
MoveToEx(hdc, m_draw[i].x, m_draw[i].y, NULL);
LineTo(hdc, m_draw[i + 1].x, m_draw[i + 1].y);
}
}
}
SelectObject(hdc, OldPen);
DeleteObject(currentPen);
m_draw.clear();
EndPaint(hWnd, &ps);
}
break;
...
return 0;
}
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.