Should I be using SendDlgItemMessage or is there a wrapper for this in WTL?

1.1k views Asked by At

I added a Listbox control to a dialog resource called IDC_LIST1. Should I be interacting with this control using SendDlgItemMessage(), or is there a better way with WTL? Here are my event handlers. It is nothing fancy yet!

LRESULT OnAddItem(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    SendDlgItemMessage(IDC_LIST1, LB_INSERTSTRING, (WPARAM) 0, (LPARAM)_T("Hi"));
    return 0;
}

LRESULT OnRemoveItem(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    // Get selected item
    int item = SendDlgItemMessage(IDC_LIST1, LB_GETCURSEL, (WPARAM) 0, (LPARAM) 0);
    // Remove the item at the index of the selected item
    SendDlgItemMessage(IDC_LIST1, LB_DELETESTRING, (WPARAM) 0, (LPARAM)item);
    return 0;
}
2

There are 2 answers

0
Alain Rist On

The WTL suggested way is as follow:

class CMyDlg : public CDialogImpl<CMyDlg>
{
public:
    enum {IDD = IDD_MYDLG};
    CListBox m_lb1;
// ...
    BEGIN_MSG_MAP(CMyDlg)
        MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
        COMMAND_ID_HANDLER(ID_ADDITEM, OnAddItem)
        COMMAND_ID_HANDLER(ID_REMOVEITEM, OnRemoveItem)
        // ...
    END_MSG_MAP()
// ...
    LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
    {
        m_lb1.Attach(GetDlgItem(IDC_LIST1));
        // ...
    }
    LRESULT OnAddItem(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
    {
        return m_lb1.AddString(_T("Hi"));
    }
    LRESULT OnRemoveItem(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
    {
        return m_lb1.DeleteString(m_lb1.GetCurSel());
    }
// ...
};

WTL support classes for common and Windows controls are in atlctrls.h, you may also have a look at WTL for MFC Programmers, Part IV - Dialogs and Controls.

0
asdfjklqwer On

You can use WTL::CListBoxT as a wrapper around a Win32 listbox... for this you need the listbox's HWND which you can obtain using GetDlgItem.

CListBoxT offers InsertString and DeleteString methods.