(转)VC中让CListBox带有复选框

(转)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中均测试通过。

 

(转者注:不要在MFC中定义ListBox的变量,否则会报错!)。

 

 

posted on 2011-10-20 16:25  海阔天  阅读(3137)  评论(0编辑  收藏  举报

导航