Sub class a  List and Edit Boxes inside a Combo

I needed to subclass list and edit boxes for one of my projects.  I found this useful article in the MSDN. I thought it might interest some of you.

 

Create a class derived from CComboBox: 

In this sample, I followed these steps:

1. Added a new class CmcCombo derived from CComboBox. Add two members in CmcCombo class:

// Implementation

public:

virtual ~CmcCombo();

CEdit m_edit;

CListBox m_listbox;

2. Override OnCtlColor and OnDestroy and write this below code:

HBRUSH CmcCombo::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) 

{

if (nCtlColor == CTLCOLOR_EDIT)

{

//[ASCII 160][ASCII 160][ASCII 160]Edit control

if (m_edit.GetSafeHwnd() == NULL)

m_edit.SubclassWindow(pWnd->GetSafeHwnd());

}

else if (nCtlColor == CTLCOLOR_LISTBOX)

{

//ListBox control

if (m_listbox.GetSafeHwnd() == NULL)

m_listbox.SubclassWindow(pWnd->GetSafeHwnd());

}

HBRUSH hbr = CComboBox::OnCtlColor(pDC, pWnd, nCtlColor);

return hbr;

}

void CmcCombo::OnDestroy() 

{

if (m_edit.GetSafeHwnd() != NULL)

m_edit.UnsubclassWindow();

if (m_listbox.GetSafeHwnd() != NULL)

m_listbox.UnsubclassWindow();

CComboBox::OnDestroy();

}

 

Now you can use this class in your projects. 

How to use this class?

1. Include mycombo.h class in your project and create a public instance of the class: CmcCombo myCombo;

2. Create the combo box now. You can write this code on your OnInitDiaog:

// TODO: Add extra initialization here

myCombo.Create( WS_CHILD|WS_VISIBLE , CRect(20, 40, 200, 200 ), this, IDC_COMBO1);

myCombo.AddString("First Item");

myCombo.AddString("Second Item");

myCombo.AddString("Third Item");

myCombo.AddString("Forth Item");

myCombo.SetCurSel(0);