CListCtrl: How to maintain scroll position?
Asked Answered
B

2

11

I have a CListCtrl (report style) where I clear the list and repopulate it at certain times. I'd like to maintain the vertical scroll position when doing this. I see there are a couple methods that look promising:

EnsureVisible()
GetScrollPos()
SetScrollPos()
GetScrollInfo()
GetTopIndex()
Scroll()

I'm trying GetScrollPos() and then SetScrollPos() but it doesn't appear to be working. What is the simple correct way to save a scroll position and then later restore it?

UPDATE

Actually it seems I can get to save the scroll position GetScrollPos() and then SetScrollPos() to restore it, however it literally just seems to set the scroll bar position and does not actually scroll the items of my CListCtrl.

UPDATE 2

The Scroll() method seems to correctly scroll the scrollbars and the contents. However it takes a CSize object as it's argument. So the question would be how to translate between the CSize and the output of either GetTopIndex or GetScrollInfo/Pos.

Bio answered 29/9, 2011 at 22:51 Comment(0)
I
20

I've done that in the past. IIRC, the trick consisted in:

int topIndex= m_List.GetTopIndex();
RenewContents();
m_List.EnsureVisible(m_List.GetItemCount() - 1); // Scroll down to the bottom
m_List.EnsureVisible(topIndex);// scroll back up just enough to show said item on top
Intromission answered 30/9, 2011 at 14:44 Comment(3)
Great this works. I'd prefer a solution using Scroll() but this does the job. Do you know off hand what happens if after you renew the contents of the list you have less items then nTopIndex?Bio
I guess EnsureVisible(nTopIndex) won't have any effect. You'll end up with a list scrolled down to the bottom.Intromission
And why did M$ not bother to offer a SetTopIndex method ? :-(Pronghorn
G
0

Another way to do it is like so:

CRect r;
m_lcList.GetItemRect(0, r, LVIR_BOUNDS);
int scrollPos = m_lcList.GetTopIndex() * r.Height();
RenewContents();
m_lcList.Scroll(CSize(0, scrollPos));
Grouping answered 26/3, 2020 at 3:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.