CListBox用法總結

CListBox用法總結
用法
屬性Style
Selection
Single — 單選
Multiple — 多選(LBS_MULTIPLESEL)
None — 不可選(LBS_NOSEL)
Sort
對應Style: LBS_SORT

Insert Item
int AddString(LPCTSTR lpszItem);
int InsertString(int nIndex,
LPCTSTR lpszItem);

Delete Item
int DeleteString(UINT nIndex);
//清空
void ResetContent();

Selection
int 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
// 獲取Text
void GetText(int nIndex,
CString& rString) const;
// Get/Set item associated data
DWORD_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”));

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章