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.
LVM_GETITEMPOSITION
or LVM_GETITEMRECT
to obtain the items position. LVM_SCROLL
to scroll the list so that your item is the top item. 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);
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.