在開發中,大部分情況控件是直接通過rc文件創建的,但也有時候需要在程序中通過CreateWindow來創建控件,下面以Button控件爲例說明子類化控件的兩種方法。
class CButtonImpl :
public CWindowImpl<CButtonImpl, CButton>
{
public:
CButtonImpl(void)
{
}
~CButtonImpl(void)
{
}
BEGIN_MSG_MAP(CButtonImpl)
MESSAGE_HANDLER(WM_GETDLGCODE, OnGetDlgCode)
DEFAULT_REFLECTION_HANDLER()
END_MSG_MAP()
……
};
方法一:使用DDX
class CTestDlg:
public CDialogImpl<CTestDlg>,
public CWinDataExchange<CTestDlg>,
{
BEGIN_MSG_MAP(CTestDlg)
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
END_MSG_MAP()
BEGIN_DDX_MAP(CTestDlg)
DDX_CONTROL(IDC_BUTTON, m_button)
END_DDX_MAP()
……
CButtonImpl m_button;
}
LRESULT CTestDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
DoDataExchange(FALSE);
return bHandled = FALSE;
}
方法二:使用SubclassWindow
class CTestDlg:
public CDialogImpl<CTestDlg>
{
BEGIN_MSG_MAP(CTestDlg)
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
END_MSG_MAP()
……
CButtonImpl m_button;
}
LRESULT CTestDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
HWND hButton = CreateWindow(TEXT("BUTTON"), _T("test"), WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON, 0, 0, 0, 0, m_hWnd, (HMENU)0, hInst, 0); //程序中創建Button
m_button.SubclassWindow(hButton );//子類化
}