Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / MFC

CComboBox with CheckBox like an Item

5.00/5 (7 votes)
4 Dec 2020CPOL1 min read 9K   499  
CheckBox as an item in CComboBox
In this tip, you will find an implementation of control CComboBox with checkbox list.

Introduction

This example shows how to implement your own combobox control with check boxes like a list item.

Using the Code

There was a need to create a combobox with the ability to select several elements.
Since the MFC does not have such a control, I had to implement my control on the basis of a combobox.

This control is based on standard CComboBox.

For using it, just create a combobox in your form with special attributes:

  • Owner Draw - Variable
  • Has Strings - True

Image 1

Include Combo.h and Combo.cpp to your project.

In these files, ChkCombo class is described.

Create the example of this class in your application.

C++
ChkCombo m_Combo;

The next step for using it is that you have to associate the standard ComboBox with this class.

C++
void CCCOMBODlg::DoDataExchange(CDataExchange* pDX)
{
    DDX_Control(pDX, IDC_COMBO1, m_Combo);
                ......
    CDialogEx::DoDataExchange(pDX);
}

So, now all ready for using this control.

At first, you need to add some strings in ChkCombo and for example, check some items.

C++
m_Combo.AddString(L"Red");
m_Combo.AddString(L"Green");
m_Combo.AddString(L"Blue");
m_Combo.AddString(L"Black");
m_Combo.AddString(L"White");
m_Combo.AddString(L"Yellow");
m_Combo.AddString(L"Brown");

m_Combo.SetCheck(0, TRUE);
m_Combo.SetCheck(1, TRUE);
m_Combo.SetCheck(2, TRUE);

For send events, this control has a special message with code THIS_CHECKED.

This message will be sent every time you check/uncheck some item.

Example of how to use it:

C++
BEGIN_MESSAGE_MAP(CCCOMBODlg, CDialogEx)
...........................................................
    ON_MESSAGE(THIS_CHECKED, &CCCOMBODlg::OnChecked)

...........................................................

END_MESSAGE_MAP()

LRESULT CCCOMBODlg::OnChecked(WPARAM wp, LPARAM lp)
{
    int ID = (DWORD)lp;
    int index = LOWORD(wp);
    bool flag = HIWORD(wp);
    wchar_t text_s[32];
    memset(text_s, 0, 32 * sizeof(wchar_t));
    wsprintf(text_s, L"%d __ %d", index, flag);
    if(ID == IDC_COMBO1)
        GetDlgItem(IDC_STATIC_CHK)->SetWindowText(text_s);
    return 0;
}

This example shows how to get control ID and get information about what item changed and the current state.

Image 2

I hope this class can help you in your work. :)

History

  • 4th December, 2020: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)