Moving selection of CListCtrl
December 3rd, 2006
tag: CListCtrl, SetItemState, SetSelectionMark
When you try to move the item selection of a CListCtrl object, you should remember to call SetSelectionMark. If not, the program will not work as you think. It will only work once and won’t work any longer.
The reason is that even you have called SetItemState and the selection was changed in visiable, but the selection mark still keeps the old value.
The solution is to call the SetSelectionMark function after SetItemState.
Here is a short example.
void CTestListDlg::OnBtnMoveNextItem()
{
int curSel = m_list.GetSelectionMark();
int nCount = m_list.GetItemCount();
m_list.SetItemState(curSel, 0, LVIS_SELECTED);
curSel ++;
if (curSel>= nCount) curSel=0;
m_list.SetItemState(curSel, LVIS_SELECTED,LVIS_SELECTED);
m_list.SetSelectionMark(curSel);
m_list.SetFocus();
}
{
int curSel = m_list.GetSelectionMark();
int nCount = m_list.GetItemCount();
m_list.SetItemState(curSel, 0, LVIS_SELECTED);
curSel ++;
if (curSel>= nCount) curSel=0;
m_list.SetItemState(curSel, LVIS_SELECTED,LVIS_SELECTED);
m_list.SetSelectionMark(curSel);
m_list.SetFocus();
}