下面的线条绘制代码有什么错误?
void GxDrawLine(HWND wnd, INT x0, INT y0, INT x1, INT y1, UINT line_thickness, UINT col) {
COLORREF color = (COLORREF) col;
HPEN pen = NULL;
if (line_thickness == 1) {
SetDCPenColor(GetDC(wnd), color);
} else {
pen = CreatePen(PS_SOLID, line_thickness, color);
SelectObject(GetDC(wnd), pen);
}
MoveToEx(GetDC(wnd), x0, y0, NULL);
LineTo(GetDC(wnd), x1, y1);
if (pen) {
SelectObject(GetDC(wnd), GetStockObject(DC_PEN));
DeleteObject(pen);
}
}
HWND wnd1 = CreateWindowExW(0, wc1.lpszClassName, L "Button",
WS_TABSTOP | WS_CHILD | WS_VISIBLE, 10, 10,
60, 60, wnd, NULL, wc.hInstance, & a); //NULL);
GxDrawLine(wnd1, 0, 0, 0, 48, 1, 0xf5f5f5);
GxDrawLine(wnd1, 0, 0, 48, 0, 1, 0xf5f5f5);
GxDrawLine(wnd1, 48, 0, 48, 48, 1, 0xf5f5f5);
GxDrawLine(wnd1, 0, 48, 48, 48, 1, 0xf5f5f5);
答案 0 :(得分:0)
在未释放DC =>内存泄漏
的情况下,您不得调用 GetDC(wnd) n次。固定代码=>
void GxDrawLine(HWND wnd, INT x0, INT y0, INT x1, INT y1, UINT line_thickness, UINT col)
{
HPEN hPenOld = NULL ;
COLORREF crColorOld = NULL;
HDC hDC = GetDC(wnd);
HPEN pen = NULL;
if (line_thickness == 1)
{
hPenOld = (HPEN)SelectObject(hDC, (HGDIOBJ)GetStockObject(DC_PEN));
COLORREF crColorOld = SetDCPenColor(hDC, col);
}
else
{
pen = CreatePen(PS_SOLID, line_thickness, col);
hPenOld = (HPEN)SelectObject(hDC, pen);
}
MoveToEx(hDC, x0, y0, NULL);
LineTo(hDC, x1, y1);
SetDCPenColor(hDC, crColorOld);
SelectObject(hDC, hPenOld);
if (pen)
DeleteObject(pen);
ReleaseDC(wnd, hDC);
}