我在名为IDC_LIST1
的对话框资源中添加了一个列表框控件。我应该使用SendDlgItemMessage()
与该控件进行交互,还是使用WTL有更好的方法?这是我的事件处理程序。还算不错!
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;
}
最佳答案
WTL建议的方式如下:
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());
}
// ...
};
atlctrls.h中提供了针对通用控件和Windows控件的WTL支持类,您还可以查看WTL for MFC Programmers, Part IV - Dialogs and Controls。