2

I am trying to write a program that selects and focuses a specific item in a list view.

Why is calling ListView_SetSelectionMark (or sending LVM_SETSELECTIONMARK) not working to set focus on a list view item? After calling ListView_SetSelectionMark, the focus remains where it was rather than changing to the new location; when I press an arrow key it moves from the previously focused item rather than the item I specified.

Here is my snippet of code that selects and focuses an item:

ListView_SetItemState(this->m_hwndChild, index, LVNI_SELECTED, LVNI_SELECTED);
ListView_SetSelectionMark(this->m_hwndChild, index);
ListView_EnsureVisible(this->m_hwndChild, index, false);
SetFocus(this->m_hwndChild);

Here is a full gist. Each time you press Ctrl-R, it selects a random item of the list view.

yonran
  • 18,156
  • 8
  • 72
  • 97

1 Answers1

3

The SelectionMark has nothing to do with focus. It merely indicates which item starts a multiple selection.

You need to use the LVIS_FOCUSED item state instead:

ListView_SetItemState(this->m_hwndChild, index, LVNI_SELECTED | LVNI_FOCUSED, LVNI_SELECTED | LVNI_FOCUSED);
ListView_EnsureVisible(this->m_hwndChild, index, false);
SetFocus(this->m_hwndChild);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Thanks! I guess I didn’t think to set the LVIS_FOCUSED list view item style since I knew that setting the similar TVIS_SELECTED tree view item style is insufficient. – yonran May 13 '15 at 04:22