0

I develop a simple program in MFC (Visual Studio 2013) for WinCE 2013, using GDI methods for drawing on device context. Unfortunatelly when I try to call SelectObject on context device handle i get error: "error C2248: 'CObject::CObject' : cannot access private member declared in class 'CObject"

I attach one of functions which calls SelectObject method.

    BOOL Druk::DrawGrid(CDC hDC,int start_x, int start_y, int limit_x, int limit_y, int width)
{
    CPen pen;
    COLORREF linecol;
    pen.CreatePen(PS_SOLID, width, NULL);
    hDC.SelectObject(&pen);
    for (float i = start_y; i < limit_y; i += 5 * MILIMETER)
    {
        hDC.MoveTo(start_x, i);
        hDC.LineTo(limit_x, i);
    }
    for (float j = start_x; j < limit_x; j += 5 * MILIMETER)
    {
        hDC.MoveTo(j, start_y);
        hDC.LineTo(j, limit_y);

    }
    for (float i = start_x; i < limit_x; i += MILIMETER)
    {
        for (float j = start_y; j < limit_y; j += MILIMETER)
        {
            hDC.MoveTo(i, j);
            hDC.LineTo(i + 1, j);
        }
    }

    return TRUE;
}

I try to google this error but I cannot find sth what can help me.

1 Answers1

6

Your code for SelectObject() looks fine to me. HOWEVER, passing a CDC by value is a big error. You should pass it by reference or pass a pointer to a CDC. I would expect to maybe see an error for when the argument CDC hDC tries to make a copy. The copy constructor and assignment operator for CObject are declared private and unimplemented. You cannot make a copy of them. Instead, change the signature of your function to:

BOOL Druk::DrawGrid(CDC& hDC,int start_x, int start_y, int limit_x, int limit_y, int width)
{
// your code
}

You also have some other problems... you need to save the originally selected pen and then select it back into the CDC at the end....

CPen* pOldPen = hdc.SelectObject(&pen);

at the end

hdc.SelectObject(pOldPen);
Joseph Willcoxson
  • 5,853
  • 1
  • 15
  • 29
  • 2
    Years ago I posted [this answer](https://stackoverflow.com/a/28858986/1889329) that offers rationale for why MFC is designed this way. – IInspectable Nov 26 '20 at 09:28
  • Additionally, `hDC` is also very bad name for the parameter. I thought it was of the `HANDLE` type. – sergiol Feb 03 '21 at 14:28