如何禁用 CListCtrl 选择选项

2022-01-12 00:00:00 c++ mfc clistctrl

我不知道如何禁用 CListCtrl 选择选项.我想覆盖 CListCtrl 类方法或处理任何窗口命令?谢谢.

I don't know how to disable the CListCtrl select option. I want to override the CListCtrl class method or handle any window command ? Thanks.

推荐答案

如果你想阻止用户在 CListCtrl 中选择一个项目,你需要从 CListCtrl 派生你自己的类 并为 LVN_ITEMCHANGING 通知添加消息处理程序.

If you want to stop the user selecting an item in a CListCtrl, you need to derive your own class from CListCtrl and add a message handler for the LVN_ITEMCHANGING notification.

所以,一个示例类 CMyListCtrl 会有一个头文件:

So, an example class CMyListCtrl would have a header file:

MyListCtrl.h

MyListCtrl.h

#pragma once

class CMyListCtrl : public CListCtrl
{
    DECLARE_DYNAMIC(CMyListCtrl)

protected:
    DECLARE_MESSAGE_MAP()

public:
    // LVN_ITEMCHANGING notification handler
    afx_msg void OnLvnItemchanging(NMHDR *pNMHDR, LRESULT *pResult);
};

然后是 MyListCtrl.cpp:

And then MyListCtrl.cpp:

#include "MyListCtrl.h"

IMPLEMENT_DYNAMIC(CMyListCtrl, CListCtrl)

BEGIN_MESSAGE_MAP(CMyListCtrl, CListCtrl)
    ON_NOTIFY_REFLECT(LVN_ITEMCHANGING, &CMyListCtrl::OnLvnItemchanging)
END_MESSAGE_MAP()

void CMyListCtrl::OnLvnItemchanging(NMHDR *pNMHDR, LRESULT *pResult)
{
    // LVN_ITEMCHANGING notification handler
    LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);

    // is the user selecting an item?
    if ((pNMLV->uChanged & LVIF_STATE) && (pNMLV->uNewState & LVNI_SELECTED))
    {
        // yes - never allow a selected item
        *pResult = 1;
    }
    else
    {
        // no - allow any other change
        *pResult = 0;
    }
}

因此,例如,您可以将普通的 CListCtrl 添加到对话框中,然后为它创建一个成员变量(默认情况下它将是 CListCtrl)然后编辑您的对话框的头文件到 #include "MyListCtrl.h 并将列表控件成员变量从 CListCtrl 更改为 CMyListCtrl.

So you can, for example, add a normal CListCtrl to a dialog, then create a member variable for it (by default it will be CListCtrl) then edit your dialog's header file to #include "MyListCtrl.h and change the list control member variable from CListCtrl to CMyListCtrl.

相关文章