Link to home
Start Free TrialLog in
Avatar of kmcdonagh
kmcdonagh

asked on

How to get index for selcted item in CListCtrl using arrow key

I hvae currently implemented a list control that displays a textual description for each item when it is clicked by the mouse.
I would like this description to also be displayed when an item is selected using the arraow keys.

I have tried the following but this doesn't seem to work.

int nCurSel = m_ExceptionListCtrl.GetNextItem(-1 , LVNI_FOCUSED   | LVNI_SELECTED);

It always seems to hold the previous one that was selected and so the descriptions are wrong.

Any help would be greatly appreciated.
Thanks
Avatar of Yechezkel
Yechezkel

Where are you trying this?
Avatar of kmcdonagh

ASKER

Inside GetSelectedItem
?

CListCtrl doesn't have a GetSelectedItem.

Do you mean your own GetSelectedItem function? That doesn't help me much. I assume your function is getting called from a message handler. Which message? Or if your function is called from somewhere else, how do you know when to call it?
The list control is within a CPropertyPage and the code submitted above is called within the OnKeydownMapList
in the property page.
Avatar of zzynx
Hi,

I think it will work if you place your code in the OnItemChangedXXX() function (triggered when the user makes a new selection in the list control [LVN_ITEMCHANGED]).

Bye.
2 kmcdonagh
>It always seems to hold the previous one that was selected
I think you call GetNextItem in the time when item state is not actualized. You can test it in addition for test each item state in the loop:

state = GetItemState(i, LVIS_SELECTED | LVIS_FOCUSED);

//index = GetHotItem();?

But better use WM_NOTIFY with LVN_ODSTATECHANGED like zzynx wrote.
Hi,

I guess, it will be better idea to loop thru and get the selected item as the key pressed may be to go down or up in the list control. In that case, ur code looks like

If ur GetSelectedItem() is in some dialog/propertysheet class

int CMyDlg::GetSelectedItem()
{
     int nItemCount = m_ctrlList.GetItemCount();
     
     for(int nIndex = 0; nIndex < nItemCount; nIndex++)
     {
          if(m_ctrlList.GetItemState(nIndex, LVIS_SELECTED))
          {
               return nIndex;
          }
         
          return -1;
     }
}

If ur GetSelectedItem() is within the list control derived class
int CMyListCtrlClass::GetSelectedItem()
{
     int nItemCount = GetItemCount();
     
     for(int nIndex = 0; nIndex < nItemCount; nIndex++)
     {
          if(GetItemState(nIndex, LVIS_SELECTED))
          {
               return nIndex;
          }
         
          return -1;
     }
}

The return value gives u the selected item index.

Try it out.
VinExpert
ASKER CERTIFIED SOLUTION
Avatar of zzynx
zzynx
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial