在 cwnd 中绘制 mfc 组件

paint mfc components inside cwnd

我创建了一个 cwnd class,它显示了一个内部有按钮的 retangle,但我不想自己绘制按钮,而是想委托给按钮组件。

原样....

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);**
    }

}

如我所愿....

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() !!!!!!!

    }
}

请问,我该怎么做?

Ps.: 不幸的是我无法使用对话框 class

您不想调用按钮绘制方法。

为 WM_CREATE 创建处理程序 (ON_WM_CREATE(), OnCreate(LPCREATESTRUCT lpcs) ...)

在您的 OnCreate 处理程序中,创建按钮...

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;
}

显然更改按钮的标题、坐标和 ID。

之后,您无需执行任何操作。该按钮将自己绘制为 parent window 的 child。