基本用法
屬性StyleSelection Single --- 單選 Multiple --- 多選(LBS_MULTIPLESEL) None --- 不可選(LBS_NOSEL)Sort 對應Style: LBS_SORT
Insert Itemint AddString(LPCTSTR lpszItem);int InsertString(int nIndex, LPCTSTR lpszItem);
Delete Itemint DeleteString(UINT nIndex);//清空void ResetContent();
Selectionint GetCurSel( ) const;int SetCurSel(int nSelect);int GetSelCount( ) const;int GetSelItems(int nMaxItems, LPINT rgIndex) const;程式碼範例:擷取選中項並輸出假設CListBox控制項變數名為m_lbTest// 1.Selection = Single-----------------------------------int nSelIndex = m_lbTest.GetCurSel();if (nSelIndex == LB_ERR)//no item is currently selected{AfxMessageBox(TEXT("no item is currently selected"));}else{CString cstr;m_lbTest.GetText(nSelIndex, cstr);AfxMessageBox(cstr);}// 2.Selection = Multiple----------------------------------int nSelCnt = m_lbTest.GetSelCount();if (nSelCnt == LB_ERR) //the list box is a single-selection list box{AfxMessageBox(TEXT("the list box is a single-selection list box"));return;}if (nSelCnt == 0)//no item is currently selected{AfxMessageBox(TEXT("no item is currently selected"));return;}int* pnSelIndex = new int[nSelCnt];m_lbTest.GetSelItems(nSelCnt, pnSelIndex);for (int i=0; i<nSelCnt; ++i){CString cstr;m_lbTest.GetText(pnSelIndex[i], cstr);AfxMessageBox(cstr);}delete[] pnSelIndex;Other// 擷取Textvoid GetText(int nIndex, CString& rString) const;// Get/Set item associated dataDWORD_PTR GetItemData(int nIndex) const;int SetItemData(int nIndex, DWORD_PTR dwItemData);注意:1.GetItemData在沒有通過SetItemData設定每一項的關聯資料時返回NULL.2.對應的GetItemDataPtr,SetItemDataPtr其實和GetItemData,SetItemData本質上是一模一樣的 我們可以看下源碼int CListBox::SetItemDataPtr(int nIndex, void* pData){ return SetItemData(nIndex, (DWORD_PTR)(LPVOID)pData); } 看來增加這兩個函數只是使意義更明確些,有點不懂微軟了。動態建立CListBox控制項
黑色非標準3D邊框:CListBox *pMyListBox = new CListBox();pMyListBox->Create(WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_BORDER | LBS_NOTIFY | LBS_MULTIPLESEL,CRect(10, 10, 100, 100),this,1234);pMyListBox->SetFont(this->GetFont());pMyListBox->AddString(TEXT("123"));pMyListBox->AddString(TEXT("456"));pMyListBox->AddString(TEXT("789"));標準3D邊框:CListBox *pMyListBox = new CListBox();pMyListBox->CreateEx( WS_EX_CLIENTEDGE, TEXT("LISTBOX"), TEXT(""),WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_BORDER | LBS_NOTIFY | LBS_MULTIPLESEL,10, 10, 100, 100,this->GetSafeHwnd(),(HMENU)1234);pMyListBox->SetFont(this->GetFont());pMyListBox->AddString(TEXT("123"));pMyListBox->AddString(TEXT("456"));pMyListBox->AddString(TEXT("789"));