CPen* hOldPen;
CPen hPen(PS_SOLID, 2, RGB(0,0,255));
hOldPen=(CPen*)dc.SelectObject (&hPen); use hPen hPen.DeleteObject();
dc.SelectObject(hOldPen);
一定要删除!!
CPen hPen(PS_SOLID, 2, RGB(0,0,255));
hOldPen=(CPen*)dc.SelectObject (&hPen); use hPen hPen.DeleteObject();
dc.SelectObject(hOldPen);
一定要删除!!
CPen->Create(...);
CPen * OldPen = dc->SelectObject(myPen);
...
delete myPen;
This is unnecessarily complex code. At least part of the confusion is that the SelectObject method wants a CPen * (or in general, a "Tool *"), which leads programmers to believe that they must supply a CPen * variable. Nothing in the specification of the call requires that the object be allocated on the heap; only that a pointer to an object be provided. This can be done by doingCPen myPen(...);
CPen * OldPen = dc->SelectObject(&myPen);
...
dc->SelectObject(OldPen);
This is much simpler code; it doesn't call the allocator. And the parameter &myPen satisfies the requirement of a CPen *. Since pens and other GDI tools are often created "on the fly" and discarded afterwards, there is no need to allocate them on the heap. When the destructor is called when you leave scope, the HPEN underlying the CPen is normally destroyed--but see below for when it is not!
CPen->Create(...);
CPen * OldPen = dc->SelectObject(myPen);
...
delete myPen;
This is unnecessarily complex code. At least part of the confusion is that the SelectObject method wants a CPen * (or in general, a "Tool *"), which leads programmers to believe that they must supply a CPen * variable. Nothing in the specification of the call requires that the object be allocated on the heap; only that a pointer to an object be provided. This can be done by doingCPen myPen(...);
CPen * OldPen = dc->SelectObject(&myPen);
...
dc->SelectObject(OldPen);
This is much simpler code; it doesn't call the allocator. And the parameter &myPen satisfies the requirement of a CPen *. Since pens and other GDI tools are often created "on the fly" and discarded afterwards, there is no need to allocate them on the heap. When the destructor is called when you leave scope, the HPEN underlying the CPen is normally destroyed--but see below for when it is not!
void CMONEView::OnMouseMove(UINT nFlags, CPoint point)
{
CClientDC dc(this); CPen* hOldPen;
CPen hPen(PS_SOLID, 2, RGB(0,0,255));
hOldPen=(CPen*)dc.SelectObject (&hPen);
hPen.DeleteObject(); .
.
.
.
dc.SelectObject(hOldPen);
CView::OnMouseMove(nFlags, point);
}
用
CPen myPen(...);
CPen * OldPen = dc->SelectObject(&myPen);
...
dc->SelectObject(OldPen);
OldPen->DeleteObject()
{
CClientDC dc(this); CPen* hOldPen;
CPen hPen(PS_SOLID, 2, RGB(0,0,255));
hOldPen=(CPen*)dc.SelectObject (&hPen); .
.
.
.
hPen.DeleteObject();
dc.SelectObject(hOldPen);
CView::OnMouseMove(nFlags, point);
}
{
CClientDC dc(this); CPen* hOldPen;
CPen hPen(PS_SOLID, 2, RGB(0,0,255));
hOldPen=(CPen*)dc.SelectObject (&hPen); .
.
.
.
dc.SelectObject(hOldPen);
hPen.DeleteObject();
CView::OnMouseMove(nFlags, point);
}try it again