【发布时间】:2012-05-18 09:13:41
【问题描述】:
我正在开发一个 win32/MFC 项目。 我有一个自定义 CListCtrl 控件,我必须不时添加一些字符串。 我绝对需要对动态添加到我的 CListCtrl 的项目执行一些操作。
基本上,我需要:
- 检测单个元素的添加;
- 检索 _single items_ 立即之后(理想情况下,在 InsertItem() 调用之后不久);
- 在地图中存储单个项目的值,我将使用它来执行其他操作。
我考虑过覆盖方法 DrawItem()。但 OnDraw 事件 似乎 不适用于我的 CListCtrl。
永远不会生成事件。
重要提示:请注意,MyCustomCListCtrl 的“On Draw Fixed”属性设置为 True,但“View" 属性NOT设置为报告。
所以,我决定处理 NW_CUSTOMDRAW 事件,编写我的 CustomDraw 处理程序,如 here 和 here 所述:
Here你可以查看另一个代码示例。
然后,我需要一种从 CListCtrl 中检索单个 itemID 的方法。
更准确地说,我需要一种方法从 NMHDR 结构中获取单个项目 ID。
我该怎么做? 我只能获得我添加的 LAST 项的 ID。 我确定这是一个我找不到的简单错误。
下面的示例代码:
包含CList Ctrl的Dialog的来源:
/* file MyDlg.cpp */
#include "stdafx.h"
#include "MyDlg.h"
// MyDlg dialog
IMPLEMENT_DYNAMIC(MyDlg, CDialog)
MyDlg::MyDlg(CWnd* pParent)
: CDialog(MyDlg::IDD, pParent)
{
}
MyDlg::~MyDlg()
{
}
void MyDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LIST1, listView); /* listView is a MyCustomCListCtrl object */
}
BEGIN_MESSAGE_MAP(MyDlg, CDialog)
ON_BN_CLICKED(IDC_BUTTON1, &MyDlg::OnBnClickedButton1)
END_MESSAGE_MAP()
BOOL MyDlg::OnInitDialog()
{
CDialog::OnInitDialog();
return TRUE;
}
/* OnBnClickedButton1 handler add new strings to MyCustomCListCtrl object */
void MyDlg::OnBnClickedButton1()
{
listView.InsertItem(0, "Hello,");
listView.InsertItem(1, "World!");
}
我的自定义 CList Ctrl 来源:
/* file MyCustomCListCtrl.cpp */
#include "stdafx.h"
#include "MyCustomCListCtrl.h"
MyCustomCListCtrl::MyCustomCListCtrl()
{
}
MyCustomCListCtrl::~MyCustomCListCtrl()
{
}
BEGIN_MESSAGE_MAP(MyCustomCListCtrl, CListCtrl)
//{{AFX_MSG_MAP(MyCustomCListCtrl)
//}}AFX_MSG_MAP
// ON_WM_DRAWITEM() /* WM_DRAWITEM NON-AVAILABLE */
ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnCustomDraw)
END_MESSAGE_MAP()
// 'Owner Draw Fixed' property is already TRUE
/* void CTranslatedCListCtrl::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
bool inside = true; /* Member function removed: I never enter here... */
} */
void MyCustomCListCtrl::OnCustomDraw(NMHDR* pNMHDR, LRESULT* pResult)
{
/* Here, I must retrieve single strings added to my MyCustomCListCtrl object */
LPNMLISTVIEW plvInfo = (LPNMLISTVIEW)pNMHDR;
LVITEM lvItem;
lvItem.iItem = plvInfo->iItem; /* Here I always get _the same_ ID: ID of last element...*/
lvItem.iSubItem = plvInfo->iSubItem; // subItem not used, for now...
int MyID = 0;
this->GetItem(&lvItem); // There mai be something error here?
MyID = lvItem.iItem;
CString str = this->GetItemText(MyID, 0); /* ...due to previous error, here I will always get the last string I have added("World!") */
// Immediately after obtaining ALL IDS, I can Do My Work
*pResult = 0;
}
感谢任何帮助!
附: 请不要给我这样的提示:
- 将“Own Draw Fixed”属性设置为 True;
- 检查您是否插入了“ON_WMDRAWITEM()”行
- 将您的 CListCtrl 转换为报告;
我已经尝试了一切... :-)
谢谢大家!
它
【问题讨论】:
标签: events mfc ondraw win32gui clistctrl