将图形对象选入设备上下文

本主题适用于使用图形对象在窗口中设备上下文。 在 创建图形对象,必须选择到设备上下文来的默认位置存储对象存在后:

void CNewView::OnDraw(CDC* pDC)
{
   CPen penBlack;  // Construct it, then initialize 
    if(penBlack.CreatePen(PS_SOLID, 2, RGB(0,0,0)))
    {
        // Select it into the device context 
        // Save the old pen at the same time
        CPen* pOldPen = pDC->SelectObject(&penBlack);

        // Draw with the pen
        pDC->MoveTo(20,20);
        pDC->LineTo(40,40);

        // Restore the old pen to the device context
        pDC->SelectObject(pOldPen);
    }
    else
    {
        // Alert the user that resources are low
    }
}

生存期图形对象

SelectObject 返回的“图形对象是临时文件”。也就是说,当下次程序获取空闲时,它将删除 CWinApp 类的成员函数。OnIdle 只要您在单个函数使用 SelectObject 返回的对象,而无需返回控件的主消息循环,则不会有问题。

您想进一步了解什么?

请参见

概念

图形对象