mfccwnd

paint mfc components inside cwnd


I create a cwnd class that shows a retangle with a button inside, but instead of draw a button by myself I would like to delegate to button component.

As is ....

class ExampleControl : public CWnd
{
    void ExampleControl::OnPaint()
    {
        CPaintDC dc(this);

        CRect rc(this);
        CDC memDC;
        memDC.CreateCompatibleDC(&dc);

        m_bmpCache.DeleteObject();
        m_bmpCache.CreateCompatibleBitmap(&dc, rc.Width(), rc.Height());

        OnDraw(&memDC);
    }

    void ExampleControl::OnDraw(CDC* pDC)
    {
        CRect rcClient(this);

        // draw background
        pDC->FillSolidRect(rcClient, GetSysColor(COLOR_WINDOW));

        // draw border
        COLORREF borderColor = RGB(0,0,255);
        pDC->Draw3dRect(0, 0, rcClient.Width(), rcClient.Height(), borderColor, borderColor);

        **//draw button
        //OK this draw a button ... but I would like to write 
        //CRect rect(10,10,25,15);
        //pDC->DrawFrameControl(rect, DFC_BUTTON, DFCS_BUTTONPUSH);**
    }

}

As I would like to be ....

class ExampleControl : public CWnd
{
    //instantiate and call myButton.Create(...)
    CButton myButton;

    void ExampleControl::OnPaint()
    {
        CPaintDC dc(this);

        CRect rc(this);
        CDC memDC;
        memDC.CreateCompatibleDC(&dc);

        m_bmpCache.DeleteObject();
        m_bmpCache.CreateCompatibleBitmap(&dc, rc.Width(), rc.Height());

        OnDraw(&memDC);
    }

    void ExampleControl::OnDraw(CDC* pDC)
    {
        CRect rcClient(this);

        // draw background
        pDC->FillSolidRect(rcClient, GetSysColor(COLOR_WINDOW));

        // draw border
        COLORREF borderColor = RGB(0,0,255);
        pDC->Draw3dRect(0, 0, rcClient.Width(), rcClient.Height(), borderColor, borderColor);

        //draw button, using the mfc component
        //!!!! myButton.OnPaint() !!!!!!!

    }
}

Please, how can I do it?

Ps.: I can not use a Dialog class unfortunately


Solution

  • You don't want to call the button paint method.

    Create a handler for WM_CREATE (ON_WM_CREATE(), OnCreate(LPCREATESTRUCT lpcs) ...)

    In your OnCreate handler, create the button...

    BEGIN_MESSAGE_MAP(CExampleControl, CWnd) // in your .cpp implementation file
    // ... other handlers
       ON_WM_CREATE()
    END_MESSAGE_MAP()
    
    int CExampleControl::OnCreate(LPCREATESTRUCT lpcs)
    {
       __super::OnCreate(lpcs);
        myButton.Create(_T("My caption"), WS_CHILD|WS_VISIBLE, CRect(0, 0, 100, 100),  this, 101);
       return 0;
    }
    

    Obviously change the caption, coordinates, and ID of the button.

    After that, you won't need to do anything. The button will draw itself as a child of the parent window.