List control LVM_SETTOPINDEX needed

2019-06-26 17:40发布

问题:

The list-view control has the LVM_GETTOPINDEX message that allows to get the index of the topmost visible item.

Now I need to set the topmost visible item, but surprisingly there is no LVM_SETTOPINDEX message which would be natural.

Is there an easy clean way to set the topmost item?

My list-control is always in report mode.

回答1:

  1. Use LVM_GETITEMPOSITION or LVM_GETITEMRECT to obtain the items position.
  2. Use LVM_SCROLL to scroll the list so that your item is the top item.


回答2:

First, it may NOT be possible. For example, if the list doesn't have enough items after your top index to fill the page.

As there is no direct way, you can count the number of items on the page, add that count to your index and call EnsureVisible(). This will make your sure that your top is above visible page. The next EnsureVisible() for your item will bring it into the view, at the top of the page. Of course, you would need to block updates to avoid jerking of the screen.

Example (updated by Vlad):

void CDlg::SetTopIndex(int top)
{
    int bottom = min(top + m_List.GetCountPerPage(), m_List.GetItemCount() - 1);
    m_List.SetRedraw(FALSE);
    m_List.EnsureVisible(bottom, TRUE);
    m_List.EnsureVisible(top, FALSE);
    m_List.SetRedraw(TRUE);
}


回答3:

This function does the job:

void SetTopIndex(CListCtrl & listctrl, int topindex)
{
  int actualtopindex = listctrl.GetTopIndex();
  int horspacing;
  int lineheight;
  listctrl.GetItemSpacing(TRUE, &horspacing, &lineheight);

  CSize scrollsize(0, (topindex - actualtopindex) * lineheight);
  listctrl.Scroll(scrollsize);
}

No parameter sanitation is done here.

Thanks to David Heffernan and Remy Lebeau for giving me the idea.