在运行时,我正在尝试使用 MFC 创建一个单列自定义CListCtrl
(或者CMFCListCtrl
,但不是CheckListBox
- 我希望将来能够添加多个列)。使用LVS_EX_CHECKBOXES
样式强制所有项目都具有复选框。所需的控件应如下所示(item1 和 item3 有复选框,item2 没有):
从用户的角度来看,所需的列表控件应该这样创建:
int main() {
MyCListCtrl list_control;
list_control.AddItem("item1", true) // true indicates checkbox presence
list_control.AddItem("item2", false) // false - item without checkbox
list_control.AddItem("item3", true) // true indicates checkbox presence
}
到目前为止,我能够创建这样的控件,但是在调用基类方法LVS_OWNERDRAWFIXED
时添加会触发失败的断言:CListCtrl::DrawItem
// MyCListCtrl.h
class MyCListCtrl : public CListCtrl {
public:
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) override {
// if the item should be without a checkbox, here I want to move it a few pixels
// to the left so that the checkbox is hidden
...
CListCtrl::DrawItem(lpDrawItemStruct); // call base's DrawItem - without this
// there's no exception but the listbox appears empty
}
};
BOOL MyCDialogEx::OnInitDialog() {
CDialogEx::OnInitDialog();
...
// list being defined somewhere in the header file
list->Create(WS_CHILD | WS_VISIBLE | WS_BORDER | LVS_REPORT | LVS_NOCOLUMNHEADER |
LVS_OWNERDRAWFIXED, // for DrawItem invocation
rect, this, SOME_ID);
list->SetExtendedStyle(list->GetExtendedStyle() | LVS_EX_CHECKBOXES);
// add 1 mandatory column because of LVS_REPORT style
LVCOLUMN lvColumn;
lvColumn.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH;
lvColumn.fmt = LVCFMT_LEFT;
lvColumn.cx = rect.Width() - 20; // also, how to make this column fit the width exactly?
lvColumn.pszText = nullptr;
list->InsertColumn(0, &lvColumn);
// for now only add 1 testing item and make his checkbox disappear by moving the
// whole item to the left in DrawItem method (called by the system), so that the text
// is aligned to the left list border
list->InsertItem(0, "item1");
...
}
这就是我的(不工作的)解决方案的样子,如果你知道如何解决这个问题,甚至可能以更简单的方式,请告诉我。谢谢。
编辑
在@Landstalker 的帮助下,我现在可以使用自定义绘图擦除复选框,但我仍然需要将文本移到左侧(因此它取代了不存在的复选框,如上图所示)。当前解决方案导致以下结果:
这是通过像这样处理 NM_CUSTOMDRAW 消息来实现的:
void MyCListCtrl::OnCustomDraw(NMHDR* pNMHDR, LRESULT* pResult)
{
*pResult = CDRF_DODEFAULT; // default windows painting
LPNMLVCUSTOMDRAW lpn = (LPNMLVCUSTOMDRAW)pNMHDR;
if (CDDS_PREPAINT == lpn->nmcd.dwDrawStage)
{
*pResult = CDRF_NOTIFYITEMDRAW; // notify on every item
}
else if (CDDS_ITEMPREPAINT == lpn->nmcd.dwDrawStage)
{
int row = lpn->nmcd.dwItemSpec;
if (row == 1) {
lpn->nmcd.rc.left -= 16; // not working
lpn->rcText.left -= 16; // not working
SetItemState(row, INDEXTOSTATEIMAGEMASK(0),
LVIS_STATEIMAGEMASK); // erase checkbox
}
}
}