TIP: Autoscrolling ListView Conrol

Azrael

Member
Joined
Feb 19, 2003
Messages
7
Hello,

Not sure if this has been done before although a cursory search revealed nothing, so here goes.

Problem:

When adding items to a listview control they are appended to the list at the bottom (in detail view). The problem is that if you are wanting focus to be on the latest entry it can be abit of a bind, because focus stays at the beginning of the list. We can access the WndProc method to play with this...


A Solution:

The problem with the control is that the WndProc is protected and so we have to subclass the ListView control and decorate it with a method called AddItem (for instance) thus:

C#:
public class ScrollerListView : ListView
{
   // values obtained from winusr.h
   const int WM_SCROLL = 0x0115; 
   const IntPtr SB_BOTTOM = (IntPtr) 7;

   public void AddItem( ListViewItem new_item )
   {
      // add the item to the items collection
      Items.Add( new_item );
      
      // have to Create a message
      Message msg = Message.Create(
         Handle,          // the hwnd handle
         WM_VSCROLL,      // uMsg 
         SB_BOTTOM,       // wParam
         IntPtr.Zero );   // null as not sent by scrollbar

      // call protected WndProc method
      WndProc( ref msg );
   }
}

WndProc is implemented in the base class to this control so we dont have to worry about it. We could implement our own, overriding it if we wished to handle certain windows messages ourselves...

Cheers

PS - and of course itd be much more graceful to have the winusr definitions elsewhere - rather disappointingly C# doesnt provide them for you...
 
Last edited by a moderator:
Back
Top