尝试在Windows API中使用C和GDI创建基本绘图程序。想法是用户单击并拖动以创建矩形或任何其他选定的形状。大小由用户单击和释放的位置指定(就像任何绘图程序一样)。我遇到了一个问题,即用户绘制的第一个形状将被绘制到屏幕上,但是任何连续的形状都不会。我最初没有在WM_PAINT中绘制形状,但是我在另一个线程上读到了我需要做的事情,因此我创建了一个结构来存储有关已绘制的对象的信息,并且每次收到WM_PAINT消息时都会绘制这些信息。
这是我的WM_PAINT代码
case WM_PAINT:
{
for (int i = 0; i < drawingcount; i++)
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
HPEN hMyPen = CreatePen(mydrawings[i].style, mydrawings[i].thick, RGB(0,255,0));
HPEN hOldPen = SelectObject(hdc, hMyPen);
if (mydrawings[i].shape == RECTANGLE)
{
Rectangle(hdc, mydrawings[i].start_x, mydrawings[i].start_y, mydrawings[i].end_x, mydrawings[i].end_y);
}
else if (mydrawings[i].shape == ELLIPSE)
{
Ellipse(hdc, mydrawings[i].start_x, mydrawings[i].start_y, mydrawings[i].end_x, mydrawings[i].end_y);
}
else if (mydrawings[i].shape == LINE)
{
MoveToEx(hdc, mydrawings[i].start_x, mydrawings[i].start_y, 0);
LineTo(hdc, mydrawings[i].end_x, mydrawings[i].end_y);
}
SelectObject(hdc, hOldPen);
DeleteObject(hMyPen);
//DeleteObject(hOldPen);
EndPaint(hwnd, &ps);
}
}
break;
这里是WM_LBUTTONUP(一旦用户完成绘制形状)
case WM_LBUTTONUP:
{
yendclick = GET_Y_LPARAM(lParam);
xendclick = GET_X_LPARAM(lParam);
mydrawings[drawingcount].shape = selected_shape;
mydrawings[drawingcount].start_x = xclick;
mydrawings[drawingcount].start_y = yclick;
mydrawings[drawingcount].end_x = xendclick;
mydrawings[drawingcount].end_y = yendclick;
mydrawings[drawingcount].thick = thickness;
mydrawings[drawingcount].style = style;
drawingcount++;
SendMessage(hwnd, WM_PAINT, wParam, lParam);
}
结构和枚举声明:
typedef enum myshape
{
RECTANGLE,
ELLIPSE,
LINE,
MAX_SHAPE
} shape;
typedef struct drawing
{
int start_x;
int start_y;
int end_x;
int end_y;
int thick;
int style;
shape shape;
} drawings;
非常感谢任何指导!
答案 0 :(得分:2)
不要使用PostMessage WM_PAINT,而是使用InvalidateRect和UpdateWindow。另见:why not to send WM_PAINT manually