Introduction
It extends the ListView
control and adds an EnsureVisible
method to scroll horizontally to a subitem.
Background
I often use The Code Project to find good samples, but I didn't find one for this. So I just want to give something back.
Using the Code
The native Windows message to scroll the listview is:
const Int32 LVM_FIRST = 0x1000;
const Int32 LVM_SCROLL = LVM_FIRST + 20;
[DllImport("user32")]
static extern IntPtr SendMessage(IntPtr Handle, Int32 msg, IntPtr wParam,
IntPtr lParam);
private void ScrollHorizontal(int pixelsToScroll)
{
SendMessage(this.Handle, LVM_SCROLL, (IntPtr)pixelsToScroll,
IntPtr.Zero);
}
The public
method to call with item to scroll to is as follows:
public void EnsureVisible(ListViewItem item, int subItemIndex)
{
if (item == null || subItemIndex > item.SubItems.Count - 1)
{
throw new ArgumentException();
}
item.EnsureVisible();
Rectangle bounds = item.SubItems[subItemIndex].Bounds;
bounds.Width = this.Columns[subItemIndex].Width;
ScrollToRectangle(bounds);
}
private void ScrollToRectangle(Rectangle bounds)
{
int scrollToLeft = bounds.X + bounds.Width + MARGIN;
if (scrollToLeft > this.Bounds.Width)
{
this.ScrollHorizontal(scrollToLeft - this.Bounds.Width);
}
else
{
int scrollToRight = bounds.X - MARGIN;
if (scrollToRight < 0)
{
this.ScrollHorizontal(scrollToRight);
}
}
}
}
History
- 30th September, 2008: Initial post