在运行时创建CWnd派生控件

时间:2015-03-02 11:59:34

标签: c++ dynamic mfc custom-controls cwnd

我正在尝试在运行时创建CWnd派生类,但CWnd::Create失败。我不知道为什么。以下是显示问题的最小代码:

MFCTestApplicationDlg.h

#pragma once

class c_CustomButton : public CButton
{
protected:
    DECLARE_MESSAGE_MAP()

    virtual void PreSubclassWindow();

public:
    c_CustomButton();
    virtual ~c_CustomButton();
};


class TestWindow : public CWnd
{
public:
    TestWindow();
    virtual ~TestWindow();

protected:
    DECLARE_MESSAGE_MAP()
    DECLARE_DYNCREATE(TestWindow)  
};

// CMFCTestApplicationDlg dialog
class CMFCTestApplicationDlg : public CDialogEx
{
...
}

MFCTestApplicationDlg.cpp

//

#include "stdafx.h"
#include "MFCTestApplication.h"
#include "MFCTestApplicationDlg.h"
#include "afxdialogex.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

/*==========================================================================*/
c_CustomButton::c_CustomButton()
{
}

/*==========================================================================*/
c_CustomButton::~c_CustomButton()
{
}

BEGIN_MESSAGE_MAP(c_CustomButton, CButton)
END_MESSAGE_MAP()

/*==========================================================================*/
void c_CustomButton::PreSubclassWindow()
{
    CButton::PreSubclassWindow();

    ModifyStyle(0, BS_OWNERDRAW);
}

IMPLEMENT_DYNAMIC(TestWindow, CWnd)

TestWindow::TestWindow()
{

}

TestWindow::~TestWindow()
{
}


BEGIN_MESSAGE_MAP(TestWindow, CWnd)
END_MESSAGE_MAP()

void CMFCTestApplicationDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);

    c_CustomButton* pColoredButton = new c_CustomButton;
    pColoredButton->Create((LPCTSTR)"", 0, CRect(), this, 0);// successeded
    pColoredButton->SetWindowTextW((LPCTSTR)"test");

    TestWindow* pTestWindow = new TestWindow;
    pTestWindow->Create((LPCTSTR)"TestWindow", (LPCTSTR)"TestWindowName", 0, CRect(), this, 0);// failed
    pTestWindow->SetWindowText((LPCTSTR)"test");
}

void CMFCTestApplicationDlg::DoDataExchange(CDataExchange* pDX)中,我尝试创建一个CButton派生类对象和CWnd派生类对象。第一个成功创建,但CWnd派生类对象无法创建。这段代码怎么了?

0 个答案:

没有答案