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.
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);