CListCtrl的查找定位

// 简单的查找函数
// FindString(CListCtrl& , 查找内容 , 开始位置 , 到达底部时是否从头查找)

int FindString(CListCtrl& list,LPCTSTR str,int startIndex,BOOL warp /* = TRUE */){
 int colCount = list.GetHeaderCtrl()->GetItemCount();
 CString* field = new CString[colCount];

 int index;
 if(startIndex < 0) index = 0;
 else index = startIndex + 1;

 BOOL isFind = FALSE;
 int out = -1;

 for(; index < list.GetItemCount(); index ++){
  for(int col = 0; col < colCount; col ++)
   field[col] = list.GetItemText(index,col);

  for(int col = 0; col < colCount; col ++){
   if(field[col].Find(str) != -1){
    out = index;
    isFind = TRUE;
    break;
   }
  }

  if(isFind) break;
 }

 delete[] field;
 field = 0;

 if(warp)
  if(!isFind)
   list.SetItemState(-1,0,LVIS_SELECTED);

 return out;


/*************************************************/

//测试
CListCtrl& list;    // 需要查找的LIST
CString str = "test";  //需要查找的字符串
int index = -1;  //开始位置

index = FindString(list,str,index,TRUE);
if(index != -1){
  list.EnsureVisible(index,FALSE);
  list.SetItemState(index,LVIS_SELECTED,LVIS_SELECTED);
  list.SetFocus();
}

你可能感兴趣的:(VC/MFC)