Answer the question
In order to leave comments, you need to log in
How to correctly draw a line in WINAPI?
When clicking, a line should be drawn from the point where the mouse was pressed and end at the point where the mouse was released. In my case, nothing happens, I just can not understand what is missing.
LONG WINAPI WndProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
BOOL fDraw = FALSE;
POINT ptPrevious = { 0 };
HPEN Pen = CreatePen(PS_SOLID, 3, RGB(0, 0, 255));
switch (Message) {
case WM_LBUTTONDOWN: {
fDraw = TRUE;
ptPrevious.x = LOWORD(lParam);
ptPrevious.y = HIWORD(lParam);
break;
}
case WM_LBUTTONUP: {
if (fDraw)
{
hdc = GetDC(hWnd);
MoveToEx(hdc, ptPrevious.x, ptPrevious.y, NULL);
LineTo(hdc, LOWORD(lParam), HIWORD(lParam));
ReleaseDC(hWnd, hdc);
}
fDraw = FALSE;
break;
}
case WM_PAINT: {
if (fDraw)
{
hdc = GetDC(hWnd);
MoveToEx(hdc, ptPrevious.x, ptPrevious.y, NULL);
LineTo(hdc, ptPrevious.x = LOWORD(lParam),
ptPrevious.y = HIWORD(lParam));
ReleaseDC(hWnd, hdc);
}
break;
}
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, Message, wParam, lParam);
}
return 0;
}
Answer the question
In order to leave comments, you need to log in
A few comments on your code:
Pen, ptPrevious, fDraw variables are not saved between function calls, make them static or global. In the current version, your code creates a HUGE number of GDI objects.
static HPEN Pen = CreatePen(PS_SOLID, 3, RGB(0, 0, 255));
static BOOL fDraw = FALSE;
static POINT ptPrevious = { 0, 0 };
case WM_PAINT: {
PAINTSTRUCT ps;
hdc = BeginPaint(hWnd, &ps);
// TODO: рисовать здесь
EndPaint(hWnd, &ps);
break;
}
ptPrevious.x = GET_X_LPARAM(lParam);
ptPrevious.y = GET_Y_LPARAM(lParam);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question