MFC › 4. Dialogs and Controls
Common Controls: List, Tree, Combo
CListCtrl, CTreeCtrl, CComboBox and notification messages.
Explanation
Controls are child windows with their own classes: standard ones (CButton, CEdit, CListBox, CComboBox, CStatic) and the common controls from comctl32 (CListCtrl, CTreeCtrl, CTabCtrl, CProgressCtrl, CSliderCtrl, CSpinButtonCtrl, CDateTimeCtrl, CToolTipCtrl, CImageList). Declare the common-control header #include <afxcmn.h> and call InitCommonControlsEx (the wizard does).
To use a control in a dialog:
- Place it in the dialog editor and give it an ID (
IDC_LIST). - Add a control variable with
DDX_Control(pDX, IDC_LIST, m_list). - Initialize it in
OnInitDialog. - React to events through the message map.
Notifications from a control reach its parent:
- Simple controls send
WM_COMMANDnotifications:ON_BN_CLICKED(id, fn),ON_EN_CHANGE,ON_CBN_SELCHANGE,ON_LBN_DBLCLK. - Common controls send
WM_NOTIFYwith a structure:ON_NOTIFY(code, id, fn)wherefnisvoid Fn(NMHDR*, LRESULT*); cast theNMHDR*to the specific struct (NMLISTVIEW*,NMTREEVIEW*).
Key operations:
CListCtrl(report view):InsertColumn,InsertItem,SetItemText,SetItemData,GetNextItem(-1, LVNI_SELECTED),DeleteAllItems,SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES),SortItems.CTreeCtrl:InsertItem(text, hParent),GetSelectedItem,GetItemText,SetItemData,Expand.CComboBox:AddString,SetCurSel,GetCurSel,GetLBText.
Example
#include <afxwin.h>
#include <afxcmn.h>
class CBrowseDlg : public CDialog {
public:
enum { IDD = IDD_BROWSE };
explicit CBrowseDlg(CWnd* pParent = nullptr) : CDialog(IDD, pParent) {}
protected:
CListCtrl m_list;
CTreeCtrl m_tree;
CComboBox m_combo;
void DoDataExchange(CDataExchange* pDX) override {
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_FILELIST, m_list); // control variables
DDX_Control(pDX, IDC_FOLDERTREE, m_tree);
DDX_Control(pDX, IDC_SORTCOMBO, m_combo);
}
BOOL OnInitDialog() override {
CDialog::OnInitDialog();
m_list.SetExtendedStyle(m_list.GetExtendedStyle() | LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES);
m_list.InsertColumn(0, _T("Name"), LVCFMT_LEFT, 160);
m_list.InsertColumn(1, _T("Size (KB)"), LVCFMT_RIGHT, 80);
const TCHAR* names[] = { _T("readme.txt"), _T("main.cpp"), _T("app.rc") };
const int sizes[] = { 2, 14, 7 };
for (int i = 0; i < 3; ++i) {
int row = m_list.InsertItem(i, names[i]); // first column
CString sz; sz.Format(_T("%d"), sizes[i]);
m_list.SetItemText(row, 1, sz); // other columns
m_list.SetItemData(row, sizes[i]); // attach an application value
}
HTREEITEM root = m_tree.InsertItem(_T("C:\\"));
HTREEITEM src = m_tree.InsertItem(_T("src"), root);
m_tree.InsertItem(_T("include"), src);
m_tree.Expand(root, TVE_EXPAND);
m_combo.AddString(_T("By name"));
m_combo.AddString(_T("By size"));
m_combo.SetCurSel(0);
return TRUE;
}
afx_msg void OnListItemChanged(NMHDR* pNMHDR, LRESULT* pResult) {
LPNMLISTVIEW pNM = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
if ((pNM->uChanged & LVIF_STATE) && (pNM->uNewState & LVIS_SELECTED)) {
CString name = m_list.GetItemText(pNM->iItem, 0);
SetWindowText(_T("Selected: ") + name);
}
*pResult = 0; // always set the result
}
afx_msg void OnTreeSelChanged(NMHDR* pNMHDR, LRESULT* pResult) {
LPNMTREEVIEW pNM = reinterpret_cast<LPNMTREEVIEW>(pNMHDR);
SetWindowText(_T("Folder: ") + m_tree.GetItemText(pNM->itemNew.hItem));
*pResult = 0;
}
afx_msg void OnSortChanged() { // CBN_SELCHANGE notification
int sel = m_combo.GetCurSel();
CString text;
m_combo.GetLBText(sel, text);
AfxMessageBox(text);
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(CBrowseDlg, CDialog)
ON_NOTIFY(LVN_ITEMCHANGED, IDC_FILELIST, &CBrowseDlg::OnListItemChanged)
ON_NOTIFY(TVN_SELCHANGED, IDC_FOLDERTREE, &CBrowseDlg::OnTreeSelChanged)
ON_CBN_SELCHANGE(IDC_SORTCOMBO, &CBrowseDlg::OnSortChanged)
END_MESSAGE_MAP()
Common pitfalls
- Using a control variable before the dialog window exists (the constructor) asserts or crashes: initialize in
OnInitDialog. - A list control needs a View: Report style set in the dialog editor, or call
ModifyStyle(LVS_TYPEMASK, LVS_REPORT); otherwise columns don’t show. - Forgetting
*pResult = 0;(or the right value) in aWM_NOTIFYhandler can make the control misbehave. LVN_ITEMCHANGEDfires several times per click (deselect, select, focus). CheckuChangedanduNewState.- Item indexes change when you sort or delete rows; attach stable IDs with
SetItemData. - Filling thousands of rows one by one is slow; use
SetRedraw(FALSE)while filling, or a virtual list (LVS_OWNERDATA). - Controls require Common Controls v6 (a manifest) for modern visual styles; the wizard adds it.
Win32 vs MFC
Win32 uses SendMessage(hList, LVM_INSERTITEM, 0, (LPARAM)&lvi) with hand-filled structures. The MFC control classes wrap each message in a method. See Dialogs and DDX/DDV for the data-exchange side.
Exercises
1. Which macro handles a CListCtrl double-click notification (NM_DBLCLK)?
ON_NOTIFY(NM_DBLCLK, IDC_FILELIST, &CBrowseDlg::OnListDblClk), with a handler of the form void OnListDblClk(NMHDR*, LRESULT*).