VC中让CListBox带有复选框

项目中需要使用一个带有复选框的列表控件,没错,VB、Delphi……里现成就有,但由于项目是VC工程,VC里现成的CListBox或CListCtrl都没有复选框。说到这里,高手们可能会说,简单,自已重绘一个,或者偷懒一点的方法,也可以去网上找一个别人做好现成的类来用。

其实还有一个更轻松的方法,网上找到这样一段话:

[How to use the CCheckListBox class in a dialog box]

Create in your resource file an ordinary list box in a dialog box.Whichever other attributes that you choose, the list box must be ownerdrawn and include the hasstrings attribute. Assume that in this case, you have assigned an ID of IDC_CHECKLISTBOX to the listbox .

Create an instance of a CCheckListBox object in the header file of your dialog box.

CCheckListBox m_CheckListBox;

Over-ride OnInitDialog() in your dialog box and subclass the list box that you created in your resource file. Set the style of the check box as you wish. See the documentation provided with your compiler.

m_CheckListBox.SubclassDlgItem(IDC_CHECKLISTBOX, this);
m_CheckListBox.SetCheckStyle(BS_AUTOCHECKBOX);

Since CCheckListBox is derived from CListBox, you have access to all the class members of CListBox. Add strings to the list box using AddString() as follows.

m_CheckListBox.AddString("Test String");

CCheckListBox provides several class members that allow you to access or set the check state of the items in the list box. For example, to see whether the first item in the list box is checked (the index of the first item would be zero), use GetCheck().

int iIndex = 0;
int iState;
iState = m_CheckListBox.GetCheck(iIndex);

方法很巧,移花接木。

MFC有一个CCheckListBox类支持复选框风格,所以我们可以直接使用ListBox控件,然后初始化时把它子类化成CCheckListBox,再设置一下风格参数就行。但要注意一下,成功的关键是要修改ListBox控件的两处属性,分别是Owner draw设置为Fixed(LBS_OWNERDRAWFIXED),Has strings设置为True(LBS_HASSTRINGS),否则不成功,运行时报错。

具体实现步骤举例如下——

1、首先在窗口上拖放一个ListBox控件,假设其资源ID为IDC_LIST1;

2、如上所述修改该ListBox控件的属性(LBS_OWNERDRAWFIXED | LBS_HASSTRINGS);

3、定义CCheckListBox对象,在窗口类的头文件里;

// XXXDlg.h
CCheckListBox m_CheckList;

4、然后在CPP文件里,初始化的地方写下两行;

// XXXDlg.cpp
BOOL CXXXDlg::OnInitDialog()
{
    // ...
    m_CheckList.SubclassDlgItem(IDC_LIST1, this); // IDC_LIST1是ListBox控件的资源ID
    m_CheckList.SetCheckStyle(BS_AUTOCHECKBOX);
    // ...
}

OK,就这么简单!加几条数据看看,是不是有复选框了!

m_CheckListBox.AddString("Test String");

判断复选框是否被选中也很简单,如下:

int iIndex = 0;
int iState;
iState = m_CheckListBox.GetCheck(iIndex);

以上在VC6、8中均测试通过。

 

补充:Delphi中使TTreeView控件带有复选框的方法——

很简单,在初始化时加上这样一句就行。(TreeView1是控件名)

SetWindowLong(TreeView1.Handle, GWL_STYLE, GetWindowLong(TreeView1.Handle, GWL_STYLE) or $00000100);

不用去找什么第三方控件,或是自绘了!

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值